Field Notes
These are the lessons web game developers usually learn the hard way: from a bug report, a ruined game jam or a review that says "runs too fast on my new monitor". Each note is short, says why, and shows the fix. Most of them you have already met in this course; here they are in one place to come back to before you ship.
1. Decouple update from render
requestAnimationFrame fires at the display's refresh rate: 60 Hz on most laptops, 120 Hz on many phones and MacBooks, 144 or 240 Hz on gaming monitors, and fewer when the machine is busy. If you move things by a fixed amount per frame, the game speed depends on the screen. Here is one second of play for a ship that should move 120 pixels per second:
const SPEED = 120; // pixels per second (the design)
function perFrame(fps) { // moves 2 px every frame ("tuned on my 60 Hz laptop")
let x = 0;
for (let f = 0; f < fps; f++) x += 2;
return x;
}
function deltaTime(fps) { // moves speed * dt every frame
let x = 0;
const dt = 1 / fps;
for (let f = 0; f < fps; f++) x += SPEED * dt;
return Math.round(x * 1000) / 1000;
}
function fixedStep(fps) { // fixed 1/60 s updates, any number of renders
const STEP = 1 / 60;
let x = 0, acc = 0, updates = 0;
for (let f = 0; f < fps; f++) {
acc += 1 / fps;
while (acc >= STEP - 1e-9) { x += SPEED * STEP; acc -= STEP; updates++; }
}
return `${Math.round(x)} px in ${updates} updates`;
}
for (const fps of [30, 60, 144]) {
console.log(`${String(fps).padStart(3)} Hz | per frame: ${String(perFrame(fps)).padStart(3)} px | dt: ${deltaTime(fps)} px | fixed step: ${fixedStep(fps)}`);
} 30 Hz | per frame: 60 px | dt: 120 px | fixed step: 120 px in 60 updates
60 Hz | per frame: 120 px | dt: 120 px | fixed step: 120 px in 60 updates
144 Hz | per frame: 288 px | dt: 120 px | fixed step: 120 px in 60 updates
Per-frame movement runs the game at half speed on a struggling laptop and 2.4× speed on a 144 Hz monitor. Delta time fixes the speed; a fixed step also makes physics and collisions identical on every machine, which is why the play kit in this course uses one. Render as often as the screen wants, update at a rate you choose.
Tip: Test on two refresh rates before release. If you only have a 60 Hz screen, Chrome DevTools can't change the refresh rate, but you can temporarily change the kit's
STEPor multiplydtto see what a faster or slower display would do to frame-based code.
2. Clamp dt, or the game explodes after a pause
When a tab is in the background, or the debugger pauses, or the laptop sleeps, the next frame arrives with a dt of seconds or minutes. An accumulator will then try to run thousands of updates to "catch up", each one making the next frame slower: the spiral of death. Bodies also tunnel straight through walls with one huge step. Cap it:
const dt = Math.min((now - last) / 1000, 0.1); // never simulate more than 0.1 s per frameThe kit does exactly this. Losing a tenth of a second of game time is invisible; teleporting the player into a wall is not.
3. Pause when the tab is hidden
Browsers throttle hidden tabs: requestAnimationFrame stops completely, and timers run at most once per second (or less). Your game freezes mid-jump, and when the player comes back, the first frame has a huge dt (see note 2). Worse, music played with Web Audio keeps playing over a frozen game. Pause on visibilitychange and let the player resume on purpose:
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
state = 'paused'; // show the pause screen when they return
audioCtx?.suspend(); // stop sounds too
}
});Pause on blur as well (the kit does), so clicking another window, or the lesson text around a game frame, doesn't leave the player dying off-screen. See Pause & visibilitychange.
4. Audio needs a user gesture first
Browsers block sound until the user interacts with the page (a click, tap or key press). An AudioContext created on page load starts suspended and stays silent, and new Audio().play() rejects with NotAllowedError. The fix is to create or resume the context inside the first input handler, which a "Click to play" screen gives you for free:
let audioCtx = null;
function unlockAudio() { // call from a pointerdown/keydown handler
audioCtx ??= new AudioContext();
if (audioCtx.state === 'suspended') audioCtx.resume();
}
cv.addEventListener('pointerdown', unlockAudio);
addEventListener('keydown', unlockAudio);Also keep a mute setting and a volume slider, and never make sound essential: some players have it off.
5. Crisp pixel art: integer positions, no smoothing
A sprite drawn at x = 10.4 is resampled across two pixel columns, so pixel art looks blurry and "swims" as it moves. Two fixes, used together:
ctx.imageSmoothingEnabled = falseso scaled images use nearest-neighbour sampling (blocky, not blurry);- draw at integer coordinates:
Math.round(x). Keep the precise float position in your game state; round only when drawing.
Click the demo: both ships move at the same slow speed. The top one is drawn at its float position with smoothing on; the bottom one is rounded with smoothing off. Hold Right/Left to move them.
<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 ----
// An 8x8 ship as text: one character per pixel, '.' is transparent.
const ART = [
'...##...',
'..####..',
'.##..##.',
'########',
'##.##.##',
'########',
'.#....#.',
'##....##',
];
const sprite = document.createElement('canvas');
sprite.width = sprite.height = 8;
const sctx = sprite.getContext('2d');
ART.forEach((row, y) => [...row].forEach((c, x) => {
if (c === '#') { sctx.fillStyle = '#7cf'; sctx.fillRect(x, y, 1, 1); }
}));
let x = 40, dir = 1;
function update(dt) {
if (keys.has('ArrowRight')) dir = 1;
if (keys.has('ArrowLeft')) dir = -1;
x += dir * 7.3 * dt; // slow on purpose: sub-pixel movement shows the problem
if (x > 300) dir = -1;
if (x < 40) dir = 1;
}
function draw() {
ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#9aa3b5'; ctx.font = '13px system-ui, sans-serif'; ctx.textAlign = 'left';
ctx.fillText(`float x = ${x.toFixed(2)}, smoothing on`, 20, 30);
ctx.fillText(`Math.round(x) = ${Math.round(x)}, smoothing off`, 20, 150);
ctx.imageSmoothingEnabled = true;
ctx.drawImage(sprite, x, 45, 64, 64); // blurry and shimmering
ctx.imageSmoothingEnabled = false;
ctx.drawImage(sprite, Math.round(x), 165, 64, 64); // crisp
}
run(update, draw, 'Watch the edges · ←/→ to change direction');
</script>Remember to set imageSmoothingEnabled again after resizing the canvas: changing width or height resets every context setting. CSS can keep the displayed scaling crisp too: canvas { image-rendering: pixelated; }.
6. Handle devicePixelRatio for sharp vector graphics
On a "retina" screen one CSS pixel is 2 or 3 device pixels. A 480×270 canvas shown at 960×540 CSS pixels gets blurry text and lines. For smooth (non-pixel-art) games, size the backing store to the real pixels and scale the context once:
const dpr = Math.min(devicePixelRatio || 1, 2); // cap at 2: 3x costs a lot of fill rate
cv.width = Math.round(cssWidth * dpr);
cv.height = Math.round(cssHeight * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // keep drawing in CSS-pixel unitsPixel-art games do the opposite: keep a small fixed resolution and scale it up by a whole number.
7. Keyboard: e.code, repeat, and the page around you
- Use
e.code(KeyW,ArrowUp,Space) for movement. It names the physical key, so WASD stays in the same place on AZERTY (French) and Dvorak keyboards. Usee.keyonly for text entry or for showing the label of a key ("Press Z" isKeyWon AZERTY!). - The OS sends repeated
keydownevents while a key is held. For "jump" or "fire once", checke.repeator track "pressed this update" yourself, as the kit'spressedset does. - Arrow keys and Space scroll the page. Call
e.preventDefault()for the keys your game uses, but only while the game has focus, or the rest of the page becomes unusable. - Clear held keys on
blur. Otherwise a key released while another window had focus stays "stuck" and the player walks forever. - Let players rebind keys, and support at least arrows + WASD out of the box.
8. Embedded games must ask for focus
Games published on itch.io, Newgrounds or a blog run inside an <iframe>, just like the playgrounds in this course. Key events only reach the frame that has focus, so a game that starts on load "doesn't respond to the keyboard" until the player happens to click it. Always start with a click to play screen: it gives the frame focus, unlocks audio (note 4) and tells the player the game is ready. Give the canvas tabindex="0" so it can be focused, and show a "paused, click to resume" screen when it loses focus.
Note: A sandboxed iframe without
allow-same-origin(like these lessons, and many embed hosts) has no access tolocalStorage: touching it throws aSecurityError. Wrap storage intry/catchand fall back to memory. See Settings & Saving.
9. Garbage creates stutter
JavaScript frees memory with a garbage collector, and collection pauses the game. Allocating per frame ({ x, y } vectors, bullets.filter(...) copies, template strings for the HUD, closures in forEach) is cheap until a few thousand objects pile up and a 20–50 ms pause appears. In hot code:
- reuse objects with pools (see Shooter 4: Object Pooling);
- remove items with swap-and-pop instead of
filterorsplicein the middle; - cache HUD strings and only rebuild them when the value changes.
But measure first (Debugging & Performance). A small game creating a hundred objects per frame is fine.
10. Finish small games
- Build the ugly version first. Rectangles and beeps. If it isn't fun with boxes, art won't save it.
- Scope down twice. Your first "small" idea is a month of work; cut it until it fits a weekend.
- A game isn't done until a stranger has played it without you explaining the controls. Watch them, don't talk.
- Keep a "known bugs" list and fix the ones players hit first.
- Ship it. A finished Pong teaches more than half of an RPG. Start, pause, game over, restart, a title: that last 20% is most of the learning.
Quick checklist before you share a game
| Check | Why |
|---|---|
| Speed is the same at 30, 60 and 144 FPS | update uses dt or a fixed step |
| Switching tabs pauses the game and the sound | visibilitychange + blur |
| No sound before the first click, sound after it | autoplay policy |
| Arrow keys don't scroll the page; keys don't stick after alt-tab | preventDefault, clear keys on blur |
Works in an iframe and without localStorage |
embed hosts, private windows |
| Pixel art is crisp; text is sharp on a phone | integer positions, devicePixelRatio |
| Touch controls (or a clear "keyboard required" note) | many visitors are on phones |
| Start, pause, game over and restart screens exist | players need a way in and out |
Test yourself
A game moves the player x += 3 every frame. What happens on a 144 Hz monitor compared with 60 Hz?
- Nothing,
requestAnimationFrameis always 60 FPS - The player moves 2.4 times faster
- The player moves slower
- The game refuses to run
Which property should movement keys be read from so WASD works on AZERTY keyboards?
e.keye.codee.keyCodee.charCode
Why does a web game need a 'click to play' screen when it is embedded in an iframe?
- Canvas can't draw before a click
- The click gives the frame keyboard focus and counts as the user gesture that unlocks audio
- It is required by the HTML standard
- It makes the game load faster