PixiJS Texture Loading

PixiJS stores all its textures inside a texture cache which can be accessed in PIXI.utils.TextureCache. To load textures into the cache you need to use a loader. This can be done by creating a new Loader instance or by utilizing a pre-made shared loader.

let loader = new PIXI.Loader();
let loader = PIXI.Loader.shared;

Now you can add assets to the loader by calling the add() method on your loader, passing in the path to the asset you want to load. To respond to complete events you call the add() method on the loader’s onComplete property, passing in the handler method. Then you can initiate the load by calling load() on your loader object.

loader.add("path/to/my/texture.png");
loader.onComplete.add(handleLoadComplete);
loader.load();

Once your load complete handler is called, you can get a reference to the texture in the loader object’s resorces property. It can be referenced by the same path you used to load it. Then by access its property called texture.

function handleLoadComplete() {
	let texture = loader.resources["path/to/my/texture.png"].texture;
}

You can then use this texture object and pass it into a new Sprite instance.

let sprite = new PIXI.Sprite(texture);

Loaders have a few other events you can listen to. The onLoad event will trigger each time an asset completes loading. The onError event will trigger if an asset fails to load. The onProgress event will give you progress updates on the status of your loader.

loader.onLoad.add(handleLoad);
loader.onError.add(handleError);
loader.onProgress.add(handleProgress);

Click here to download the demo.