General know-how for making games that run in the browser with HTML5, JavaScript, Canvas 2D and WebGL. Choosing the tech (Canvas, WebGL, DOM, Phaser, PixiJS, three.js, Kaplay), the game loop, rendering performance, input for keyboard / mouse / touch / gamepad, Web Audio, asset loading, saving, screen scaling, mobile and Safari quirks, accessibility, profiling, and shipping a build. Use when bui...
Download skill (.zip) Files on GitHubHTML5 game development
Related skills, if installed: game-scaffolding (a ready project), game-architecture, game-state-management, game-mechanics, bash-web-game-checkup (finds problems + snippet fixes), bash-tv-development (Bash specifics).
1. Pick the tech
| Game | Use | Why |
|---|---|---|
| Board, card, puzzle, quiz, UI-heavy | DOM + CSS (or React) | Text, layout and accessibility for free |
| Simple 2D, up to ~1,000 sprites | Canvas 2D (plain JS) | No dependencies, easy to reason about |
| 2D with physics, tilemaps, animation, cameras | Phaser 3 | Batteries included, huge example library |
| Many 2D sprites / effects, own game logic | PixiJS | Fast WebGL renderer only |
| Tiny 2D jam games | Kaplay (Kaboom successor) | Very little code |
| 3D | three.js (+ Rapier or cannon-es for physics) | Most examples, flexible |
| 3D with built-in editor tools | Babylon.js | Physics, GUI, inspector included |
Don’t switch engines mid-project without a reason. Match the existing code. In Bash spaces with a game kit, use the kit’s engine.
2. The loop
requestAnimationFrame, neversetInterval.- Fixed-step updates for physics or anything that must be consistent (
dt = 1/60, accumulate real time, cap a frame at 0.25 s). Otherwise use variabledtin seconds and multiply every speed by it. - Update order each step: input → game logic → physics/collisions → cleanup (remove dead things) → render.
- Pause on
visibilitychange, and reset the clock on resume so there’s no hugedt.
3. Rendering performance
Canvas 2D
- Size the canvas to the CSS size ×
Math.min(devicePixelRatio, 2), and draw in game units throughsetTransform. - Pre-render static layers (background, tilemap) to an offscreen canvas once, and
drawImageit each frame. - Avoid per-frame
shadowBlur,filter, gradients and text measuring. Cache them as images. - Batch by state: draw everything with the same
fillStyleor image together. - Integer positions for pixel art (
Math.round), andimageSmoothingEnabled = false.
WebGL / three.js
- Fewer draw calls beat fewer triangles: merge static meshes, use
InstancedMeshfor repeats, share materials, use texture atlases. renderer.setPixelRatio(Math.min(devicePixelRatio, 2)). Shadows only where they matter, and keep shadow maps small.- Dispose geometries, materials and textures you remove (
.dispose()), or memory grows. - Compress textures (KTX2/Basis) and models (Draco/meshopt) for big scenes.
Everywhere
- Object pools for bullets and particles, so the garbage collector doesn’t cause stutters.
- No allocations in hot loops (
new, array spreads, closures insideupdate). - Spatial grid or hash for collisions when there are more than ~100 objects (see game-architecture).
- Profile before optimizing: DevTools → Performance, look for long frames and GC. Add a debug FPS counter behind a key.
4. Input
- Pointer events (
pointerdown/move/up) cover mouse, touch and pen. UsesetPointerCapturefor drags. - Map keys to actions, and read
e.code(layout-independent), note.key. preventDefault()on game keys (arrows, space) or the page scrolls inside iframes.- Clear held keys on
blur, otherwise keys stay stuck after alt-tab. - Touch:
touch-action: noneon the canvas, on-screen buttons at least 48–56 px, multi-touch tracked bypointerId. - Gamepad: poll
navigator.getGamepads()each frame, and use a dead zone (~0.2) on sticks. - In an iframe (Bash preview, itch.io), the keyboard only works after a click, so use a “click / tap to start” moment.
5. Audio
- Browsers block sound until a user gesture:
audioContext.resume()on the firstpointerdown/keydown. - Web Audio buffers for sound effects (instant, overlapping).
<audio>or a buffer source for music. - Ship MP3 (plays everywhere) or OGG + MP3. Keep sounds short and normalized. Always add a mute toggle and remember it.
- iOS: the hardware silent switch mutes Web Audio. Mention it if a user reports “no sound on iPhone”.
6. Assets and loading
- Relative paths only (
./assets/hero.png). Absolute paths break on itch.io, GitHub Pages and portals. - Preload what the first screen needs and show progress. Load later levels and music in the background.
- WebP images, sprite sheets / atlases, compressed audio (see bash-web-asset-shrinker).
- File names: lowercase, no spaces. Hosts are case-sensitive.
7. Screen and devices
- Pick a game resolution, scale to fit with letterboxing, and convert pointer coordinates into game units.
- Handle
resizeand orientation changes. Useenv(safe-area-inset-*)for notches. - Fullscreen:
element.requestFullscreen()from a click. iPhone Safari has no element fullscreen, so hide the button there. - Test at phone portrait (390×844), phone landscape (844×390) and desktop.
8. Saving
localStorage inside try/catch (it can be blocked), with keys prefixed by the game name, JSON with a version,
and a migration step for old saves. Never trust saved data. Check shapes and defaults on load.
9. Accessibility and comfort
Remappable or alternative keys, no essential info by color alone, readable text (≥16 px at the game’s size),
reduced flashing and shake (respect prefers-reduced-motion), pause anytime, volume control, and subtitles for spoken lines.
10. Browser quirks worth knowing
| Symptom | Usual cause |
|---|---|
| Blurry canvas | Canvas pixel size ≠ CSS size × devicePixelRatio |
| Runs double speed on 120 Hz screens | Movement per frame instead of per second |
| No sound until refresh | AudioContext never resumed after a gesture |
| Works locally, blank on itch.io | Absolute paths, wrong file-name case, index.html not at the top of the ZIP |
| ES modules fail locally | Opened via file://. Use a static server |
| Page scrolls while playing | Missing preventDefault / touch-action: none |
| Stutter every few seconds | Garbage collection: pool objects, stop allocating per frame |
| Popups don’t appear | alert/confirm/prompt are blocked in embeds. Use in-game UI |
11. Shipping
Run a checkup (bash-web-game-checkup), shrink assets, remove debug code, set a version, and test the exported build in an iframe at its embed size, then on a phone. Then publish (bash-itch-export, bash-web-deploy-anywhere).