All examples · Sprites and 2D

Layering and alpha

What this example shows

In 3D, what covers what is decided by distance to the camera and settled by the depth buffer. In 2D there is no such thing: whatever is drawn later covers what came before, and that is the whole rule. So the question "what goes in front?" is the question "what order does it draw in?".

That is zIndex. Every sprite carries one, the renderer sorts by it before drawing, and the highest number lands on top. The three squares here never move and never change opacity: the only thing that changes each second is which of them holds the high zIndex.

Worth noticing that zIndex is written straight onto the sprite createSprite returned, inside the useUpdate. Nothing needs to be notified and the sprite is not rebuilt: the renderer reads the value as it stands when the frame comes around.

Alpha is a separate thing, and it is here for a reason. It lives in the colour: each square has a fixed, different a in its tint, so you can see through them and the reordering reads without anything having to move. A transparent sprite obeys zIndex like any other.

And each one is a different colour, on purpose: see-through layers of one single colour give the same result in any order, because white over white is white over white. With three white squares the order would change every second and nothing would show it.

Starting