Pixi.js Tutorial #2: Move It, Sprite! π
May 15, 2025
Welcome back to our magical journey into browser game dev! In Part 1, we added Pixi.js to the page, created a canvas, and displayed a spinning bunny. Now, letβs load your own sprite and make it move!
π· Loading an Image with Pixi.js
Pixi has a built-in asset loader called PIXI.Assets.load
. Letβs use it to load an image.
<script>
await PIXI.Assets.load('my-sprite.png');
</script>
But weβll make it more useful by waiting for the image, then displaying it:
<script>
const app = new PIXI.Application({ width: 360, height: 540 });
document.body.appendChild(app.view);
const texture = await PIXI.Assets.load('https://pixijs.io/examples/examples/assets/bunny.png');
const sprite = new PIXI.Sprite(texture);
sprite.anchor.set(0.5);
sprite.x = app.screen.width / 2;
sprite.y = app.screen.height / 2;
app.stage.addChild(sprite);
</script>
π Make It Dance (Or Move)
To animate the sprite, use Pixi's ticker to update its position every frame.
app.ticker.add(() => {
sprite.x += 1; // move right by 1 pixel each frame
});
This will make the sprite slide smoothly to the right! You can use sprite.x
, sprite.y
, sprite.rotation
, or sprite.scale
to animate anything.
π Bonus: Bouncy Movement
Try this for a little bounce:
let direction = 1;
app.ticker.add(() => {
sprite.x += 2 * direction;
if (sprite.x > 330 || sprite.x < 30) direction *= -1;
});
β What Youβve Learned
- How to load image assets with
PIXI.Assets.load
- How to create a
PIXI.Sprite
- How to move your sprite using
ticker
Next up: Letβs make that sprite run like a proper character with animation frames! π