How to Load Images Asynchronously in Pixi.js

Loading images asynchronously to create textures in Pixi.js is essential for preventing performance stutters and ensuring a smooth user experience. This article explains how to use Pixi.js’s modern Assets utility to load an image file from a URL, convert it into a texture, and render it onto the screen using async/await syntax.

Using the Assets Utility

In modern versions of Pixi.js (v7 and v8), the Assets class is the standard and most efficient way to load external files. It manages the loading queue and automatically caches the loaded resources as textures.

Here is a complete, step-by-step example of how to load an image asynchronously and use it as a texture:

import { Application, Assets, Sprite } from 'pixi.js';

async function init() {
    // Initialize the PixiJS Application
    const app = new Application();
    await app.init({ resizeTo: window });
    document.body.appendChild(app.canvas);

    // Define the image URL
    const imageUrl = 'https://pixijs.com/assets/bunny.png';

    try {
        // Asynchronously load the image file as a texture
        const texture = await Assets.load(imageUrl);

        // Create a sprite from the loaded texture
        const sprite = new Sprite(texture);

        // Position the sprite in the center of the screen
        sprite.x = app.screen.width / 2;
        sprite.y = app.screen.height / 2;
        sprite.anchor.set(0.5);

        // Add the sprite to the stage to render it
        app.stage.addChild(sprite);
    } catch (error) {
        console.error("Failed to load image texture:", error);
    }
}

init();

Key Steps Breakdown

  1. Initialize the Application: The app.init() method is itself asynchronous in the latest Pixi.js versions, ensuring the WebGL or WebGPU context is fully set up before asset loading begins.
  2. Assets.load(): This method takes the URL of the image as an argument and returns a Promise. When the promise resolves, it returns a ready-to-use Texture object. Pixi.js automatically detects the file extension (PNG, JPG, WebP) and handles the decompression in the background.
  3. Sprite Creation: Once the promise resolves, the resulting texture is passed directly into a new Sprite constructor.
  4. Error Handling: Wrapping the asynchronous call in a try...catch block ensures that you can handle network failures, incorrect paths, or corrupted files gracefully without crashing the application.