PixiJS Getting Started

To download the latest version of PixiJS you can check the releases tab of the github repository here.

Because of browser security restrictions loading local assets directly will result in CORS errors. We’ll need to get around this in PixiJS because you can’t do much without loading textures. The easiest way to avoid this is to run your code on a server. You can run a local server if you have python installed by opening terminal navigating to your project directory and running python -m SimpleHTTPServer 8000 which will run a local server at localhost with the port defined: localhost:8000. Now simply loading this page should run the index.html file at your project directory without any issues. If you are on python version 3 you should use python3 -m http.server 8000

The quickest way to get started with PixiJS is with a helper class called PIXI.Application. This class combines and abstracts a bunch of common utilities used when making content with PixiJS.


const app = new PIXI.Application({
  view: canvas,
  width: window.innerWidth,
  height: window.innerHeight
});

It can take a number of parameters including width and height. You can also provide your own canvas element as the rendering surface as the view. If you do not provide a view, you can append the canvas created for you to the DOM using document.body.appendChild(app.view).

Next we need to load a texture into webGL. `Pixi.Texture` has a `from()` method which takes the path to the image as a prameter. Calling this returns the instance of our texture.


const texture = PIXI.Texture.from('sprite.png');

Now that we have our texture we can use it to create a sprite. `PIXI.Sprite()` takes a single parameter of a texture instance.


const img = new PIXI.Sprite(texture);

Now that we have our sprite we can set properties of it, like the x and y position. We can also set the anchor position to the center. Since it is a webGL quad the anchor coordinates for the center are 0.5 on the x and y axis. After we have it set up the way we want we can add it to the stage. The stage is also created for us with `PIXI.Application` and can be referenced by `app.stage`. By calling `addChild()` we can add objects to the stage.


img.x = app.screen.width / 2;
img.y = app.screen.height / 2;
img.anchor.x = 0.5;
img.anchor.y = 0.5;
app.stage.addChild(img);

Now you should have an image at the center of the screen.

Now we need to add some animation. Again `PIXI.Application` helps us out here by creating a `ticker` for us, which is a render loop running utilizing `requestAnimationFrame`. We can access this through `app.ticker`. Then we simply call `add()`, passing in the method that we want it to call for each animation loop.


app.ticker.add(animation);

Then we can update properties of our scene inside the animation method.


function animation() {
  img.rotation += 0.1;
}

This should have your sprite rotating in a circle around the center axis.

Click here to download the demo.