Loading images into the texture cache

Because Pixi renders the image on the GPU with WebGL, the image needs to be in a format that the GPU can process. A WebGL-ready image is called a texture. Before you can make a sprite display an image, you need to convert an ordinary image file into a WebGL texture. To keep everything working fast and efficiently under the hood, Pixi uses a texture cache to store and reference all the textures your sprites will need. The names of the textures are strings that match the file locations of the images they refer to. That means if you have a texture that was loaded from "images/cat.png", you could find it in the texture cache like this:

  1. PIXI.utils.TextureCache["images/cat.png"];

The textures are stored in a WebGL compatible format that’s efficient for Pixi’s renderer to work with. You can then use Pixi’s Sprite class to make a new sprite using the texture.

  1. let texture = PIXI.utils.TextureCache["images/anySpriteImage.png"];
  2. let sprite = new PIXI.Sprite(texture);

But how do you load the image file and convert it into a texture? Use Pixi’s built-in loader object.

Pixi’s powerful loader object is all you need to load any kind of image. Here’s how to use it to load an image and call a function called setup when the image has finished loading:

  1. PIXI.loader
  2. .add("images/anyImage.png")
  3. .load(setup);
  4. function setup() {
  5. //This code will run when the loader has finished loading the image
  6. }

Pixi’s development team recommends that if you use the loader, you should create the sprite by referencing the texture in the loader’s resources object, like this:

  1. let sprite = new PIXI.Sprite(
  2. PIXI.loader.resources["images/anyImage.png"].texture
  3. );

Here’s an example of some complete code you could write to load an image, call the setup function, and create a sprite from the loaded image:

  1. PIXI.loader
  2. .add("images/anyImage.png")
  3. .load(setup);
  4. function setup() {
  5. let sprite = new PIXI.Sprite(
  6. PIXI.loader.resources["images/anyImage.png"].texture
  7. );
  8. }

This is the general format we’ll be using to load images and create sprites in this tutorial.

You can load multiple images at the same time by listing them with chainable add methods, like this:

  1. PIXI.loader
  2. .add("images/imageOne.png")
  3. .add("images/imageTwo.png")
  4. .add("images/imageThree.png")
  5. .load(setup);

Better yet, just list all the files you want to load in an array inside a single add method, like this:

  1. PIXI.loader
  2. .add([
  3. "images/imageOne.png",
  4. "images/imageTwo.png",
  5. "images/imageThree.png"
  6. ])
  7. .load(setup);

The loader also lets you load JSON files, which you’ll learn about ahead.