Phaser 3 & PixiJS
Phaser and PixiJS are the two most widely used JavaScript 2D libraries. Phaser is a complete game framework; PixiJS is a very fast renderer that you build your own game structure around. The lesson playgrounds can't load external libraries, so the framework code here is shown as plain code you can paste into a local project. Next to it is a raw-canvas version of the same mini game that you can play here, so you can compare line by line.
Setting up a project
Both libraries are npm packages and work well with Vite:
npm create vite@latest star-collector -- --template vanilla
cd star-collector
npm install phaser # or: npm install pixi.js
npm run devPut assets (images, sounds, maps) in public/assets/ so they are served as-is. Use a dev server: browsers block loading images and JSON from file:// pages.
Phaser 3: a scene with arcade physics
A Phaser game is a configuration object plus one or more scenes. Each scene has lifecycle methods: preload loads assets, create builds the objects, update(time, delta) runs every frame. Arcade Physics gives sprites a body with velocity, gravity, world bounds and AABB collisions.
import Phaser from 'phaser';
class Play extends Phaser.Scene {
constructor() { super('play'); }
preload() {
// Real projects load files: this.load.image('star', 'assets/star.png');
// Here we draw textures in code, so no files are needed.
}
create() {
const g = this.add.graphics();
g.fillStyle(0xffb74d).fillRect(0, 0, 16, 16);
g.generateTexture('player', 16, 16);
g.clear().fillStyle(0xffd54f).fillCircle(5, 5, 5);
g.generateTexture('star', 10, 10);
g.destroy();
this.player = this.physics.add.sprite(240, 135, 'player').setCollideWorldBounds(true);
this.stars = this.physics.add.group();
for (let i = 0; i < 6; i++) {
this.stars.create(Phaser.Math.Between(20, 460), Phaser.Math.Between(40, 250), 'star');
}
this.score = 0;
this.scoreText = this.add.text(8, 8, 'Score: 0', { fontFamily: 'monospace', fontSize: '14px', color: '#ffffff' });
this.physics.add.overlap(this.player, this.stars, (player, star) => {
star.disableBody(true, true); // hide it and remove it from physics
this.score += 1;
this.scoreText.setText(`Score: ${this.score}`);
if (this.stars.countActive(true) === 0) this.scene.restart();
});
this.cursors = this.input.keyboard.createCursorKeys();
}
update(time, delta) {
const speed = 180;
this.player.setVelocity(0);
if (this.cursors.left.isDown) this.player.setVelocityX(-speed);
else if (this.cursors.right.isDown) this.player.setVelocityX(speed);
if (this.cursors.up.isDown) this.player.setVelocityY(-speed);
else if (this.cursors.down.isDown) this.player.setVelocityY(speed);
}
}
new Phaser.Game({
type: Phaser.AUTO, // WebGL if available, Canvas otherwise
width: 480,
height: 270,
backgroundColor: '#0e1018',
pixelArt: true, // nearest-neighbour scaling, no blur
physics: { default: 'arcade', arcade: { gravity: { x: 0, y: 0 }, debug: false } },
scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },
scene: [Play],
});What Phaser did for you: the loop, delta time, scaling the canvas to fit the window, keyboard handling, collision detection between a sprite and a group, and object recycling (disableBody keeps the object for reuse, like the pools in this course). Phaser 3 also has tilemaps (this.make.tilemap with Tiled JSON), cameras (this.cameras.main.startFollow), tweens (this.tweens.add), particles, sound and Matter.js physics for rotating rigid bodies.
Tip: Turn on
arcade: { debug: true }while developing: Phaser draws every body and its velocity, which finds most collision bugs in seconds.
PixiJS v8: the renderer
PixiJS draws a tree of display objects (the stage) with WebGL or WebGPU. It has no physics, scenes or game rules, so you add your own update code. Version 8 initialises asynchronously:
import { Application, Assets, Container, Graphics, Sprite, Text } from 'pixi.js';
const app = new Application();
await app.init({ width: 480, height: 270, background: '#0e1018', antialias: false });
document.body.appendChild(app.canvas);
// const texture = await Assets.load('assets/player.png'); // real projects
const player = new Graphics().rect(0, 0, 16, 16).fill(0xffb74d);
player.position.set(232, 127);
const stars = new Container();
for (let i = 0; i < 6; i++) {
const star = new Graphics().circle(0, 0, 5).fill(0xffd54f);
star.position.set(20 + i * 75, 60 + (i % 3) * 70);
stars.addChild(star);
}
const label = new Text({ text: 'Score: 0', style: { fontFamily: 'monospace', fontSize: 14, fill: '#ffffff' } });
label.position.set(8, 8);
app.stage.addChild(stars, player, label);
const keys = new Set();
addEventListener('keydown', (e) => keys.add(e.code));
addEventListener('keyup', (e) => keys.delete(e.code));
let score = 0;
app.ticker.add((ticker) => {
const dt = ticker.deltaMS / 1000; // seconds since the last frame
const speed = 180 * dt;
if (keys.has('ArrowLeft')) player.x -= speed;
if (keys.has('ArrowRight')) player.x += speed;
if (keys.has('ArrowUp')) player.y -= speed;
if (keys.has('ArrowDown')) player.y += speed;
for (const star of [...stars.children]) {
if (Math.abs(star.x - (player.x + 8)) < 12 && Math.abs(star.y - (player.y + 8)) < 12) {
star.destroy();
label.text = `Score: ${++score}`;
}
}
});What Pixi did for you: a fast renderer with batching, a scene tree (move a Container and all its children move: that is your camera), text rendering, texture loading with Assets, and a ticker. Everything game-specific (input, collision, rules) was yours, exactly as in raw canvas.
The same game in raw canvas
This is the version you can play here. Compare its size with the two above: for a small game the framework doesn't save much code. The savings appear later, with sprite sheets, tilemaps, audio, scaling and many object types.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
const player = { x: 232, y: 127, s: 16 };
let stars = [], score = 0, round = 0;
function newRound() {
round++;
stars = [];
for (let i = 0; i < 6; i++) stars.push({ x: 20 + ((i * 97 + round * 53) % 440), y: 50 + ((i * 61 + round * 29) % 200) });
}
newRound();
function update(dt) {
const sp = 180 * dt;
if (keys.has('ArrowLeft')) player.x -= sp;
if (keys.has('ArrowRight')) player.x += sp;
if (keys.has('ArrowUp')) player.y -= sp;
if (keys.has('ArrowDown')) player.y += sp;
player.x = Math.max(0, Math.min(W - player.s, player.x)); // setCollideWorldBounds(true)
player.y = Math.max(0, Math.min(H - player.s, player.y));
for (const st of stars) { // physics.add.overlap(...)
if (Math.abs(st.x - (player.x + 8)) < 13 && Math.abs(st.y - (player.y + 8)) < 13) { st.taken = true; score++; }
}
stars = stars.filter((st) => !st.taken);
if (stars.length === 0) newRound(); // scene.restart()
}
function draw() {
ctx.fillStyle = '#0e1018';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#ffd54f';
for (const st of stars) { ctx.beginPath(); ctx.arc(st.x, st.y, 5, 0, Math.PI * 2); ctx.fill(); }
ctx.fillStyle = '#ffb74d';
ctx.fillRect(Math.round(player.x), Math.round(player.y), player.s, player.s);
ctx.fillStyle = '#fff';
ctx.font = '14px monospace';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText(`Score: ${score} Round: ${round}`, 8, 8);
}
run(update, draw, 'Arrow keys: collect the stars');
</script>Phaser vs PixiJS at a glance
| Question | Phaser 3 | PixiJS v8 |
|---|---|---|
| "I want to make a game this month" | Yes: physics, scenes, audio, tilemaps included | Possible, but you assemble the parts |
| "I need 50,000 sprites or custom shaders" | Good | Excellent: that is its core strength |
| "I want my own architecture (ECS, custom physics)" | Fights you a bit | A natural fit |
| Rendering backends | WebGL, Canvas | WebGL, WebGPU |
| Typical add-ons | Plugins, Matter physics, Spine | @pixi/sound, a physics engine (Matter, Rapier), a tween library |
Note: Phaser 4, the successor to Phaser 3, replaces the renderer but keeps the same scene, physics and input concepts, so what you learn here carries over. Check the version in each tutorial you follow: many old articles target Phaser 2 (
game.state) or Pixi v7 (new Application({...})withoutawait app.init) and no longer work as written.
Test yourself
In Phaser 3, which scene method should load images and sounds?
createupdatepreloadconstructor
How is a PixiJS v8 Application started?
new Application({ width, height })and it's readyconst app = new Application(); await app.init({ ... })PIXI.start()app.run()
What does pixelArt: true in a Phaser config do?
- Converts images to pixel art
- Uses nearest-neighbour scaling so pixel art stays crisp
- Lowers the resolution
- Enables physics