Add Child to Container in Pixi.js Dynamically

In Pixi.js, you can dynamically add child objects—such as Sprites, Graphics, or other Containers—to an existing Container at runtime using the addChild() method. This article explains how to instantiate a Pixi.js container, create display objects dynamically, and inject them into the container using standard API methods.

The Basic addChild Method

To add a new object to an existing container, use the addChild() method. This method automatically places the new object at the top of the container’s rendering stack (on top of other children).

import { Container, Sprite, Texture } from 'pixi.js';

// 1. Create the parent container
const mainContainer = new Container();

// 2. Define a function to add sprites dynamically
function addDynamicChild(x, y) {
    // Create a new display object (e.g., a Sprite)
    const bunny = Sprite.from('path/to/bunny.png');
    
    // Set its properties
    bunny.x = x;
    bunny.y = y;
    
    // Dynamically append it to the existing container
    mainContainer.addChild(bunny);
}

// Example usage: adding a child on a user click
window.addEventListener('click', (event) => {
    addDynamicChild(event.clientX, event.clientY);
});

Controlling Layering with addChildAt

By default, addChild() appends the new object to the end of the children array, rendering it on top of everything else. If you need to insert a child at a specific depth or layer, use addChildAt().

// Adds the child at index 0, rendering it behind all other existing children
mainContainer.addChildAt(childObject, 0);

Adding Multiple Children Simultaneously

You can pass multiple display objects to a single addChild() call to add them all at once.

const childOne = new Sprite(texture1);
const childTwo = new Sprite(texture2);

// Add both children to the container in a single line
mainContainer.addChild(childOne, childTwo);

Dynamic Removal

To maintain performance when dynamically adding objects, you should also remove them when they are no longer needed. Use removeChild() to remove a specific object, or destroy() to clear the object from memory.

// Remove a child from the container without destroying it
mainContainer.removeChild(childObject);

// Remove all children from the container at once
mainContainer.removeChildren();