Remove Child Element from Pixi.js Stage Safely

This article provides a straightforward guide on how to safely remove a specific child element from the stage in Pixi.js. You will learn the best practices for removing display objects using built-in Pixi.js methods, preventing runtime errors, and properly managing memory to avoid performance leaks.

Standard Removal Using removeChild

The most common way to remove a specific child from the Pixi.js stage (or any Container) is by using the removeChild method. This method removes the child from the container’s render tree but keeps the object in memory for potential reuse.

// Assuming 'app' is your Pixi Application and 'sprite' is the child element
app.stage.removeChild(sprite);

Safely Checking if the Child Exists

To prevent runtime errors, it is best practice to verify that the child is actually a member of the stage before attempting to remove it. You can do this by checking the child’s parent property.

if (sprite.parent === app.stage) {
    app.stage.removeChild(sprite);
}

Alternatively, you can check if the stage contains the child using the children array:

if (app.stage.children.includes(sprite)) {
    app.stage.removeChild(sprite);
}

Removing and Destroying (Memory Management)

Simply removing a child from the stage does not delete it from memory. If you do not plan on using the element again, you must destroy it to free up GPU and CPU resources.

You can pass configuration options to the destroy method to clean up underlying textures and base textures.

// Remove from stage
app.stage.removeChild(sprite);

// Destroy the sprite and its texture to free up memory
sprite.destroy({
    children: true,      // Destroy all children if it's a container
    texture: true,       // Destroy the texture of the sprite
    baseTexture: true    // Destroy the base texture source
});

One-Step Removal and Destruction

If you want to remove the child from its parent and destroy it in a single step, you can call destroy directly on the child. Pixi.js automatically handles the removal from the parent container during the destruction process.

if (sprite.parent) {
    sprite.destroy({ children: true, texture: true });
}