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;
}
}
- The puffs sit in a row (x, y, vx, vy, r), so JS can read all of them as one
Float32Array. #[repr(C)]fixes the order ofStatus's fields, so JS knowsscoreis at byte 4.escapedcounts puffs that got away,tunneledpuffs that went through the tray.- The other exports:
step()(the same asstep_dt(1/60)),start(count, seed)to set up the puffs with repeatable random numbers (xorshift),steer(-1 | 0 | 1)for input,place_tray(x)for touch, andfog_ptr()andstatus_ptr()for the addresses.
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);
}
});
- The
Float32Arrayview is made once and points straight at Wasm memory. Every frame JS only reads it; nothing is copied. - All the puffs go into one path and one
fill(). Drawing has a cost per call too. - This is the common architecture: Wasm computes the game state and prepares what needs drawing, JS calls Canvas 2D or WebGL. Here the "draw calls sent over" are the list of puffs in memory; other games send a list of draw commands or a vertex buffer for WebGL the same way.
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);
remainderholds the time not yet simulated. On a 120 Hz screen that is one step every second frame; on a slow phone, several steps per frame.- The 0.25-second cap prevents the "spiral of death": when one frame is very late, the game doesn't try to catch up hundreds of steps at once, it just slows down for a moment.
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
});
- Input goes to Wasm when it changes, not every frame.
e.repeatignores repeated keydowns while a key is held. - Pointer events handle mouse, finger and stylus at once. Give the canvas the CSS
touch-action: noneso a finger on it doesn't scroll the page. - A sharp canvas on a phone screen:
canvas.width = Math.round(320 * devicePixelRatio)(DPR can be a fraction),canvas.style.width = '320px', thenctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0). Without that CSS size, the canvas shows 2 to 3 times bigger, not sharper. Setheightthe same way.
📌 Engines: Godot, Unity, Bevy
- Godot 4: since 4.3 its web export is single-threaded by default, so it needs no cross-origin isolation headers; the multithreaded version does. It renders with WebGL 2. According to the Godot blog (May 2024), the 4.3 web build's
.wasmis about 40 MB, 5 MB after brotli. - Unity 6 (Web platform): the build files are compressed with gzip (the default) or Brotli, and the server must send the matching
Content-Encodingheader, unless you turn on Decompression Fallback. - Bevy (Rust, ECS): built for
wasm32-unknown-unknown, then wasm-bindgen, rendering through WebGL 2 (WebGPU is still experimental), and everything on one thread on the web. - Use an engine when you need 3D, full physics, an editor, audio and many platforms. Write your own, like Catch the Fog (1,671 bytes), when the game is small and the download size matters.
📌 Phones: screens, batteries, background tabs
requestAnimationFramefollows the screen (60, 90 or 120 times a second) and stops in background tabs. A fixed timestep keeps the game speed the same on every screen, and the 0.25-second cap protects you when a tab is reopened after tens of seconds.- At a
devicePixelRatioof 3, a 320 × 200 canvas holds 9 times as many pixels. If drawing gets too heavy, lower the internal resolution. - Stop the loop when the game closes or the page is hidden (
visibilitychange), so it doesn't drain the battery.
⚠️ Fog that slips through, a blurry canvas, a loop that never stops
- An uncapped variable dt. Fog goes through the tray after one slow frame, and the score differs on every phone.
- One call per entity, or one
fill()per puff. Batch it: onestep(), one view, as few draw calls as possible. - Old views after
memory.grow. Their length is 0 and their contentsundefined, with no error. Checkfog.buffer !== x.memory.buffer. - A blurry canvas, or the page scrolling along on a phone. Scale by
devicePixelRatio, and settouch-action: none. - A loop that never stops. Keep the id from
requestAnimationFrameand callcancelAnimationFramewhen the game 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.