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:
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.
let texture = PIXI.utils.TextureCache["images/anySpriteImage.png"];
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:
PIXI.loader
.add("images/anyImage.png")
.load(setup);
function setup() {
//This code will run when the loader has finished loading the image
}
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:
let sprite = new PIXI.Sprite(
PIXI.loader.resources["images/anyImage.png"].texture
);
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:
PIXI.loader
.add("images/anyImage.png")
.load(setup);
function setup() {
let sprite = new PIXI.Sprite(
PIXI.loader.resources["images/anyImage.png"].texture
);
}
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:
PIXI.loader
.add("images/imageOne.png")
.add("images/imageTwo.png")
.add("images/imageThree.png")
.load(setup);
Better yet, just list all the files you want to load in an array inside a single add
method, like this:
PIXI.loader
.add([
"images/imageOne.png",
"images/imageTwo.png",
"images/imageThree.png"
])
.load(setup);
The loader
also lets you load JSON files, which you’ll learn about ahead.