Adding sprites to a PixiJS application

/ #PixiJS

In this part I'm going to show you how to show a sprite in the PixiJS application we created in the previous part. If you haven't already read the previous part, I suggest that you do it now.

First of all, you need an image to insert. If you want, you can download this very simple image of a butterfly. Place it in the same folder as the HTML file you created in the previous part.

Adding the code for the sprite

On the line below "document.body.appendChild(app.view);", add this code:

var butterfly = PIXI.Sprite.fromImage('butterfly.jpg');
butterfly.position.x = 300;
butterfly.position.y = 200;


This code shouldn't look too scary I hope. On the first line, we declare a variable called "butterfly". We use a module called "Sprite" from Pixi. This module contains a function called "fromImage", which is just the one we need. We pass in the path and name of the image.

The two lines below the variable declaration is used to set the position of the butterfly. We set it 300px from the left of the screen and 200px from the top of the screen. The butterfly's anchor point is at it's center, so if you set position.x to 0, you would only see half of the butterfly. If you set position.x to 100 (half of the butterfly size), it would be placed at the very left of the screen.

When the position is set, the last thing we need to do is to add it to the stage of our app. A stage is where all of the content you see is located. When you're building games or apps, it's normal to split the stage into scenes or container for better maintainability.

What's next?

Since you now know how to add a sprite to the screen, it's time to move on. In the next part, we're going to add text and text style to the app.


No comments yet...

Add comment

Subscribe to my newsletter