Gaming and Canvas with Wasm — WebAssembly

A browser game is a requestAnimationFrame loop: input, update, draw. Wasm is popular for games because motion, physics and collisions run at close to native…

Fog rolls down from the mountain, and Mrs. Sri's bamboo tray down below has to catch it. That is "Catch the Fog", the game we build in this lesson. A browser game is really a loop: read the input, move the game world forward a little, draw one frame, roughly 60 times a second. Wasm suits the moving-forward part (motion, collisions, hundreds to thousands of objects), while JavaScript and Canvas do the drawing.

The split of work is like a shadow-puppet show. The puppeteer moves every puppet behind the screen to the beat of the music. An oil lamp casts their shadows onto the screen, and the audience only ever sees those shadows. The puppeteer is the Wasm module that holds and moves every position, the lamp is JavaScript reading those positions and drawing, the screen is the canvas, and the beat of the music is the fixed timestep: the puppeteer moves on each beat, not on each flicker of the lamp.

The game loop: input, update, draw

requestAnimationFrame(fn) asks the browser to call fn just before the screen is repainted: 60 times a second on a 60 Hz screen, 120 times on a 120 Hz screen, and not at all while the tab is in the background. fn receives the current time in milliseconds.

Why Wasm is popular for games: motion, physics and collisions are the same number crunching over and over, and Wasm runs it at close to native speed with stable timing across browsers. Big game engines written in C++, such as Godot and Unity's runtime, are compiled to Wasm with Emscripten, so games can come to the web without a rewrite. Drawing still goes through browser APIs: Canvas 2D, WebGL or WebGPU.

State in linear memory

The game "Catch the Fog": fog drifts down from the mountain, and Mrs. Sri's tray at the bottom catches it. All of its state lives in the memory of the catch-the-fog Wasm module (no_std Rust, 1,671 bytes after cargo build --release):

const MAX: usize = 2000; // at most 2,000 fog puffs

/// Every puff is 5 f32 numbers in a row: x, y, vx, vy, r.
static mut FOG: [f32; MAX * 5] = [0.0; MAX * 5];

/// Read by JS every frame: tray_x, then score, escaped, tunneled, steps.
#[repr(C)]
pub struct Status { tray_x: f32, score: u32, escaped: u32, tunneled: u32, steps: u32 }

/// Move forward by dt seconds. TRAY_Y = 176, thickness 8, width 56; WIDTH x HEIGHT = 320 x 200.
#[unsafe(no_mangle)]
pub extern "C" fn step_dt(dt: f32) {
    unsafe {
        let s = &mut *core::ptr::addr_of_mut!(STATUS);
        let k = &mut *core::ptr::addr_of_mut!(FOG);
        let mut tx = s.tray_x + DIRECTION as f32 * TRAY_SPEED * dt;
        if tx < 0.0 { tx = 0.0; }
        if tx > WIDTH - TRAY_WIDTH { tx = WIDTH - TRAY_WIDTH; }
        s.tray_x = tx;
        for i in 0..COUNT {
            let o = i * 5;
            let (x0, y0, r) = (k[o], k[o + 1], k[o + 4]);
            let mut x = x0 + k[o + 2] * dt;
            let y = y0 + k[o + 3] * dt;
            if x < 0.0 { x += WIDTH; }
            if x >= WIDTH { x -= WIDTH; }
            k[o] = x;
            k[o + 1] = y;
            let above = x + r > tx && x - r < tx + TRAY_WIDTH;
            if above && y + r >= TRAY_Y && y - r <= TRAY_Y + TRAY_THICKNESS {
                s.score += 1; // touches the tray at its new position
                respawn(i, true); // reappears at the top
            } else if above && y0 + r < TRAY_Y && y - r > TRAY_Y + TRAY_THICKNESS {
                s.tunneled += 1; // jumped over the tray in a single step
            } else if y - r > HEIGHT {
                s.escaped += 1;
                respawn(i, true);
            }
        }
        s.steps += 1;
    }
}
WebAssembly.instantiate(bytes).then(({ instance }) => {
  const x = instance.exports;
  x.start(200, 2026); // 200 puffs, seed 2026
  const fog = new Float32Array(x.memory.buffer, x.fog_ptr(), 200 * 5);
  const trayX = new Float32Array(x.memory.buffer, x.status_ptr(), 1);
  const counts = new Uint32Array(x.memory.buffer, x.status_ptr(), 5); // [1] score, [2] escaped, [3] tunneled

  function draw() {
    ctx.clearRect(0, 0, 320, 200);
    ctx.beginPath();
    for (let i = 0; i < 200; i++) {
      const o = i * 5;
      ctx.moveTo(fog[o] + fog[o + 4], fog[o + 1]);
      ctx.arc(fog[o], fog[o + 1], fog[o + 4], 0, Math.PI * 2);
    }
    ctx.fill(); // one fill for every puff
    ctx.fillRect(trayX[0], 176, 56, 8);
    ctx.fillText('Score ' + counts[1], 8, 14);
  }
});

One view, not one call per puff

Another way to read the positions: three exported functions, fog_x(i), fog_y(i), fog_r(i). For 2,000 puffs that is 6,000 crossings per frame, against 0 through the view. Measured:

Per frame, 2,000 puffs Time
Reading through the view (Node 22) 0.04 ms
Reading through 6,000 calls (Node 22) 0.08 ms
step() in Wasm 0.013 ms
Drawing 2,000 circles all the way to pixels (Chromium 147 headless, forced with getImageData) about 5 ms

In this game, crossing is not the most expensive part: an export that only returns a number is very cheap per call (remember the "crossing cost" lesson: 960,000 calls took 8 ms). The heavy part is drawing: recording the Canvas commands is cheap, but turning them into pixels takes about 5 ms of the 16.7 ms frame budget, far above those 0.08 ms. The pattern still holds: one step() call per step, state read through a view, drawing gathered into as few draw calls as possible. The per-entity pattern gets expensive when every call creates a JS object, or when Wasm calls Canvas itself for every puff through glue like web-sys.

If the module calls memory.grow, the old views break. Their length becomes 0, fog[0] is silently undefined, and their methods throw TypeError: Cannot perform %TypedArray%.prototype.fill on a detached or out-of-bounds ArrayBuffer (Chromium 156's text). Make new views when fog.buffer !== x.memory.buffer.

Fixed timestep

Frames never arrive evenly spaced. If every frame moves the game forward by that frame's gap (a variable dt), the result depends on the phone. A fixed timestep moves the world in fixed steps of 1/60 of a second, as many as it takes to catch up with the clock:

const DT = 1 / 60;
let remainder = 0;
let previous = performance.now();

function frame(now) {
  remainder += Math.min((now - previous) / 1000, 0.25); // at most 15 steps to catch up
  previous = now;
  while (remainder >= DT) {
    x.step();
    remainder -= DT;
  }
  draw();
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

Before you look at the table, guess. Fog puffs fall at up to 150 pixels per second, and the tray is 8 pixels thick. A guest's phone stalls for half a second. If the game is moved forward 0.5 seconds at once, does any fog go through the tray? What if it moves forward in steps of 1/60 of a second?

Measured with 200 puffs and seed 2026, the tray standing still:

How the game moves forward Score Got away Went through
10 seconds, fixed 1/60 (600 steps) 147 556 0
10 seconds, variable dt at 20 fps (200 steps) 145 554 0
10 seconds, variable dt at 120 fps 148 556 0
1 second, then one step with dt 0.5 seconds 23 83 8
1 second, then a 0.5-second lag with the code above (15 steps of 1/60) 26 61 0

With a dt of 0.5 seconds, yes: 8 puffs go through the tray. A puff falling at 150 pixels per second jumps 75 pixels in one step, so at its old position it is above the tray and at its new one it is already below. With a fixed timestep a step moves at most 2.5 pixels, and none go through; because of the 0.25-second cap only 15 steps run and the game slows down for a moment. The first three rows also show that a variable dt gives a different score on a different phone.

Input: keyboard and touch

const keys = { ArrowLeft: -1, ArrowRight: 1 };
addEventListener('keydown', (e) => { if (e.key in keys && !e.repeat) x.steer(keys[e.key]); });
addEventListener('keyup', (e) => { if (e.key in keys) x.steer(0); });

canvas.addEventListener('pointermove', (e) => {
  const box = canvas.getBoundingClientRect();
  x.place_tray(((e.clientX - box.left) * 320) / box.width); // screen pixels to game coordinates
});

📌 Engines: Godot, Unity, Bevy

📌 Phones: screens, batteries, background tabs

⚠️ Fog that slips through, a blurry canvas, a loop that never stops

TL;DR: A browser game is a requestAnimationFrame loop: input, update, draw. Wasm is popular for games because motion, physics and collisions run at close to native speed, and C++ engines (Godot, Unity's runtime) can be compiled to Wasm with Emscripten; drawing still goes through Canvas, WebGL or WebGPU. The architecture: Wasm computes the state in linear memory (Catch the Fog, 1,671 bytes, puffs as a row of f32 x, y, vx, vy, r), JS reads a Float32Array view once per frame and draws every puff with one path. Per-entity crossings (6,000 calls, 0.08 ms) are not the most expensive part here; drawing (about 5 ms) is. Use a fixed 1/60 timestep with a 0.25-second cap: one 0.5-second step let 8 puffs through the tray, fixed steps let 0 through, and the result is the same on every screen. Send input when it changes (steer, place_tray), scale the canvas by devicePixelRatio with touch-action: none. Make new views after memory.grow. Use an engine (Godot, Unity, Bevy) for big games; for a small game, your own module is far lighter.

⚡ Wasm computes, JS draws

Write:

x.start(200, 2026); // 200 puffs, seed 2026
const fog = new Float32Array(x.memory.buffer, x.fog_ptr(), 200 * 5);

Meaning: Wasm is popular for games because motion, physics and collisions run almost as fast as native code, and C++ engines like Godot compile to Wasm with Emscripten. The fog lives in linear memory as a row of f32 numbers (x, y, vx, vy, r). JS reads it through one view without copying, then draws every puff with one fill().

⚡ Fixed timestep

Write:

remainder += Math.min((now - previous) / 1000, 0.25); // at most 15 steps to catch up
while (remainder >= DT) {
  x.step();
  remainder -= DT;
}
Guess first: the phone stutters for half a second, and the game moves forward 0.5 seconds at once. Does any fog go through the tray?

Yes: 8 puffs. Fog falling at 150 pixels per second jumps 75 pixels in one step, while the tray is only 8 pixels thick. With a fixed step of 1/60 second, each step moves at most 2.5 pixels, so none gets through.

Meaning: The 0.25-second cap prevents the "spiral of death", and the score is the same on every screen.

⚡ Input when it changes, a new view after grow

Meaning: Send input to Wasm when it changes (steer, place_tray), not every frame. If the module calls memory.grow, old views break: make a new view when fog.buffer !== x.memory.buffer.

What you will learn