How to Change Z-Index of Sibling Objects in Pixi.js
Managing the rendering order of overlapping visual elements is
essential for creating depth in 2D applications. In Pixi.js, the draw
order of display objects is determined by their position within their
parent container’s child array. This article explains how to control
this rendering order using the built-in zIndex and
sortableChildren properties, as well as how to manually
manipulate the child array for custom sorting.
Method 1: Using
zIndex and sortableChildren
The most straightforward way to manage rendering order in modern
Pixi.js is by enabling automatic sorting on the parent container. By
default, Pixi.js does not sort children by zIndex because
sorting has a minor performance cost.
To enable this feature, set the parent container’s
sortableChildren property to true. Once
enabled, you can assign integer values to the zIndex
property of any child object. Pixi.js will automatically sort the
children so that objects with lower zIndex values are
rendered behind objects with higher values.
const container = new PIXI.Container();
container.sortableChildren = true;
const background = new PIXI.Sprite(texture1);
background.zIndex = 1;
const foreground = new PIXI.Sprite(texture2);
foreground.zIndex = 2;
container.addChild(foreground);
container.addChild(background);
// Even though foreground was added first, background renders behind it due to zIndexIf you modify the zIndex of a child dynamically after
the container has already been created, Pixi.js will automatically
trigger a resort on the next render pass.
Method 2: Manual Array Manipulation
If you prefer not to use sortableChildren, you can
control the rendering order by manually arranging the elements inside
the parent’s children array. Pixi.js renders objects from
index 0 (the bottom-most layer) to index
children.length - 1 (the top-most layer).
Bringing an Object to the Front
To bring an existing child to the absolute front of the rendering
stack, you can re-add it to the parent using addChild().
This removes the child from its current position in the array and
appends it to the end.
// Moves mySprite to the very top of the container
container.addChild(mySprite);Inserting an Object at a Specific Index
To place a child at a precise depth layer, use the
addChildAt() method. This allows you to define the exact
index of the child.
// Inserts mySprite at index 0, placing it behind all other children
container.addChildAt(mySprite, 0);Swapping the Position of Two Siblings
If you need to swap the rendering order of two specific sibling
objects, you can use the swapChildren() method.
// Swaps the rendering depth of spriteA and spriteB
container.swapChildren(spriteA, spriteB);