Z-Index positioning with CreateJS
Asked Answered
P

2

5

I'm trying to set the z-index for my line Graphic(). I'm trying to set the line to be always behind the other two shapes. Two shapes and one line.

As far as I know, the first element added is z=0, the second one is z=1 and so on. Is that so? Is z=0 the top possition or is it the bottom?

I'm trying yo change their z position using stage.setChildIndex(element, z-level), is that right?

Thanks.

Peonage answered 28/8, 2013 at 16:41 Comment(1)
Can you post some code? I am not entirely sure what the expectation is.Deflective
B
4

1) The lower the index, the more in the 'back' is the item, so: 0 = bottom Please also keep in mind that setChildIndex will fail if you try something like: container.setChildIndex(child,500) if you only have 4 children, so the index you want to set the child to must not be out of range. That means if you want to sort them you should start with the lowest index (usually 0).

2) Or you could also give your objects a property like e.g.: child.zIndex = 500; and write your own sort-method to then use the sortChildren-method of the container, for example:

function sortByZ(a,b) {
    if (a.zIndex < b.zIndex) return -1;
    if (a.zIndex > b.zIndex) return 1;
    return 0;
}

myContainer.sortChildren(sortByZ);

// or a shorter version:
function sortByZ(a,b) {
    return a.zIndex - b.zIndex;
}

That way you wouldn't have to worry about setting a zIndex, that is out of bounds.

Balsamiferous answered 28/8, 2013 at 18:22 Comment(3)
And I could retrieve the number of children If I do getNumChildren(), right? Thanks olsn, not only I was mistaken about the order, but also about the index. I was doing setChildIndex(child, 200) because I thought that It would be stored in an unbounded array. Thanks!Peonage
By the way, does the index go from 0 to getNumChildren()?Peonage
Yes, that is correct. All those methods getNumChildren() setChildIndex() are basically just wrapper-functions for basic array-operations, getNumChildren() for example will simply return this.children.length - and setChildIndex() will just check for the index and do a splice-operation on the children-array - So if you want to learn something go and take a look under the hood: createjs.com/Docs/EaselJS/files/… - it is some very good code that the gskinner-team wrote :)Balsamiferous
T
4

With createjs valid values for setChildIndex() are in the range of 0 to numChildren()-1. A call such as:

container.setChildIndex(container.numChildren());

will fail.

What's more when you increase the child index - in example for a child with z-index 1 when changed to 2, the child will be placed in front of the object at index 2. In case you decrease the index moving the child backward it will be moved behind the object at the targeted position. It may add confusion when you are not sure what the initial z-index of the child is.

Thigmotaxis answered 13/6, 2015 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.