references/web-apis.md
Web APIs for Game Development
A comprehensive reference covering the web platform APIs most relevant to building browser-based games. Each section describes what the API is, why it matters for games, its key interfaces and methods, and provides brief code examples where applicable.
asm.js
What It Is
asm.js is a strict, highly optimizable subset of JavaScript designed for near-native performance. It restricts JavaScript to a narrow set of constructs -- integers, floats, arithmetic, simple functions, and heap accesses -- and disallows objects, strings, closures, and anything requiring heap allocation. The result is completely valid JavaScript that any engine can run, but that supporting engines can compile aggressively ahead of time.
Why It Matters for Games
- Near-native speed: Emscripten-compiled C/C++ game engines run with near-native performance across browsers.
- Predictable performance: The restricted feature set yields highly consistent frame rates.
- C/C++ portability: Existing native game engines can be compiled to asm.js with Emscripten and deployed on the web.
- No plugins required: Runs as standard JavaScript in every modern browser.
Key Concepts
| Concept | Description |
|---------|-------------|
| Allowed constructs | while, if, numbers (strict int/float), top-level named functions, arithmetic, function calls, heap accesses |
| Disallowed constructs | Objects, strings, closures, dynamic type coercion, heap-allocating constructs |
| Compiler toolchain | Emscripten compiles C/C++ to asm.js |
| Engine recognition | Browsers detect the "use asm" directive and apply ahead-of-time compilation |
Deprecation Notice
asm.js is deprecated. WebAssembly (Wasm) is the modern successor and offers better performance, broader tooling, and wider industry support. New projects should target WebAssembly instead.
Code Example
// asm.js module pattern (simplified)
function MyModule(stdlib, foreign, heap) {
"use asm";
var sqrt = stdlib.Math.sqrt;
var HEAP32 = new stdlib.Int32Array(heap);
function distance(x1, y1, x2, y2) {
x1 = +x1; y1 = +y1; x2 = +x2; y2 = +y2;
var dx = 0.0, dy = 0.0;
dx = +(x2 - x1);
dy = +(y2 - y1);
return +sqrt(dx * dx + dy * dy);
}
return { distance: distance };
}
Canvas API
What It Is
The Canvas API provides a means for drawing 2D graphics via JavaScript and the HTML <canvas> element. It is one of the primary rendering surfaces for browser-based games, supporting game graphics, animation, image manipulation, and real-time video processing.
Why It Matters for Games
- 2D rendering surface: The standard way to draw sprites, tilemaps, particles, and HUD elements in browser games.
- Pixel-level control: Direct access to pixel data via
ImageDatafor custom effects, collision maps, and procedural generation. - High performance: Hardware-accelerated in modern browsers, suitable for 60 fps game loops.
- Broad ecosystem: Libraries like Phaser, Konva.js, EaselJS, and p5.js build on Canvas for game development.
Key Interfaces
| Interface | Purpose |
|-----------|---------|
| HTMLCanvasElement | The <canvas> HTML element |
| CanvasRenderingContext2D | The main 2D drawing interface |
| ImageData | Raw pixel data for direct manipulation |
| ImageBitmap | Bitmap image data for efficient drawing |
| Path2D | Reusable path objects |
| OffscreenCanvas | Offscreen rendering, usable in Web Workers |
| CanvasPattern | Repeating image patterns |
| CanvasGradient | Color gradients |
| TextMetrics | Text measurement data |
Key Methods (CanvasRenderingContext2D)
fillRect(),strokeRect(),clearRect()-- rectangle operationsdrawImage()-- draw images, sprites, or other canvasesbeginPath(),arc(),lineTo(),fill(),stroke()-- path drawinggetImageData(),putImageData()-- pixel manipulationsave(),restore()-- state managementtranslate(),rotate(),scale(),transform()-- transformations
Code Example
<canvas id="game" width="800" height="600"></canvas>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
// Clear the frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw a filled rectangle (e.g., a platform)
ctx.fillStyle = "green";
ctx.fillRect(100, 400, 200, 20);
// Draw a sprite
const sprite = new Image();
sprite.src = "player.png";
sprite.onload = () => {
ctx.drawImage(sprite, playerX, playerY, 32, 32);
};
// Game loop
function gameLoop(timestamp) {
update(timestamp);
render(ctx);
requestAnimationFrame(gameLoop);
}
requestAnimationFrame(gameLoop);
CSS (Cascading Style Sheets)
What It Is
CSS is the language used to describe the presentation of web documents. In the context of game development, CSS handles styling of UI overlays, HUD elements, menus, transitions, animations, and visual effects that sit on top of or alongside the game canvas.
Why It Matters for Games
- UI and HUD styling: Style health bars, score displays, inventory panels, dialog boxes, and menus without touching the game canvas.
- CSS Animations and Transitions: Hardware-accelerated animations for UI elements (fade-ins, slide-outs, pulsing effects) with minimal JavaScript.
- CSS Transforms: Translate, rotate, scale, and skew DOM elements for visual effects and UI positioning.
- Flexbox and Grid: Lay out complex game UIs (settings panels, leaderboards, lobby screens) responsively.
- Custom Properties (CSS Variables): Theme game UIs dynamically by changing variable values at runtime.
- Pointer and cursor control: Customize or hide cursors, control pointer events on overlay elements.
- Media queries: Adapt game UI across screen sizes and device types.
Key Properties for Games
| Property / Feature | Use Case |
|--------------------|----------|
| transform | Rotate, scale, translate UI elements |
| transition | Smooth property changes (e.g., health bar width) |
| animation / @keyframes | Looping or triggered UI animations |
| opacity | Fade effects for overlays and modals |
| pointer-events | Let clicks pass through overlay layers to the canvas |
| cursor | Set custom cursors or hide the cursor (cursor: none) |
| z-index | Layer UI above the game canvas |
| position: fixed / absolute | Anchor HUD elements to viewport |
| display: flex / grid | Responsive layout for menus and panels |
| filter | Blur, brightness, contrast effects on DOM elements |
| mix-blend-mode | Blend overlay effects with the canvas |
| will-change | Hint the browser to optimize animated properties |
Code Example
/* Game HUD overlay */
.hud {
position: fixed;
top: 0;
left: 0;
width: 100%;
padding: 10px;
pointer-events: none; /* clicks pass through to canvas */
z-index: 10;
font-family: "Press Start 2P", monospace;
color: white;
text-shadow: 2px 2px 0 black;
}
/* Health bar with smooth transitions */
.health-bar {
width: 200px;
height: 20px;
background: #333;
border: 2px solid white;
}
.health-bar-fill {
height: 100%;
background: limegreen;
transition: width 0.3s ease;
will-change: width;
}
/* Pulsing damage indicator */
@keyframes damage-flash {
0%, 100% { opacity: 0; }
50% { opacity: 0.4; }
}
.damage-overlay {
position: fixed;
inset: 0;
background: red;
animation: damage-flash 0.3s ease;
pointer-events: none;
}
Fullscreen API
What It Is
The Fullscreen API provides methods to present a specific element (and its descendants) in fullscreen mode, removing all browser chrome and UI elements. It allows entering and exiting fullscreen programmatically and reports the current fullscreen state.
Why It Matters for Games
- Immersive experience: Fullscreen removes all browser distractions, providing a console-like gaming experience.
- Maximum screen real estate: The entire display is available for the game viewport.
- Games are a primary use case: The MDN documentation explicitly lists online games as a target application.
Key Interfaces and Methods
| API | Description |
|-----|-------------|
| Element.requestFullscreen() | Enters fullscreen mode. Returns a Promise. |
| Document.exitFullscreen() | Exits fullscreen mode. Returns a Promise. |
| Document.fullscreenElement | The element currently in fullscreen, or null. |
| Document.fullscreenEnabled | Boolean indicating whether fullscreen is available. |
| fullscreenchange event | Fired when fullscreen state changes. |
| fullscreenerror event | Fired if entering/exiting fullscreen fails. |
Code Example
const gameContainer = document.getElementById("game-container");
// Enter fullscreen on button click
document.getElementById("fullscreenBtn").addEventListener("click", () => {
if (document.fullscreenEnabled) {
gameContainer.requestFullscreen().catch(err => {
console.error("Fullscreen request failed:", err);
});
}
});
// Toggle fullscreen with a key press
document.addEventListener("keydown", (e) => {
if (e.key === "F11") {
e.preventDefault();
if (!document.fullscreenElement) {
gameContainer.requestFullscreen();
} else {
document.exitFullscreen();
}
}
});
// Respond to fullscreen changes (resize canvas, adjust UI)
document.addEventListener("fullscreenchange", () => {
if (document.fullscreenElement) {
resizeCanvasToFullscreen();
} else {
resizeCanvasToWindowed();
}
});
Notes
- Fullscreen can only be requested in response to a user gesture (click, key press).
- Users can always exit via the Escape key or F11.
- For embedded games in iframes, the
allowfullscreenattribute is required. - Check
Document.fullscreenEnabledbefore offering the feature in your UI.
Gamepad API
What It Is
The Gamepad API provides a standardized interface for detecting and reading input from gamepads and game controllers. It exposes button presses, analog stick positions, and controller connection events, enabling console-style controls in browser games.
Why It Matters for Games
- Console-quality input: Support Xbox, PlayStation, and generic controllers in browser games.
- Multiple controllers: Detect and handle several gamepads simultaneously for local multiplayer.
- Analog input: Read analog stick axes and pressure-sensitive triggers for nuanced control.
- Haptic feedback: Experimental support for vibration via
GamepadHapticActuator.
Key Interfaces
| Interface | Description |
|-----------|-------------|
| Gamepad | Represents a connected controller with buttons, axes, and metadata |
| GamepadButton | Represents a single button -- pressed (boolean) and value (pressure 0..1) |
| GamepadEvent | Event object for gamepadconnected and gamepaddisconnected events |
| GamepadHapticActuator | Hardware interface for haptic feedback (experimental) |
Key Methods and Events
| API | Description |
|-----|-------------|
| navigator.getGamepads() | Returns an array of Gamepad objects for all connected controllers |
| gamepadconnected event | Fired on window when a controller is connected |
| gamepaddisconnected event | Fired on window when a controller is disconnected |
Code Example
// Detect controller connections
window.addEventListener("gamepadconnected", (e) => {
console.log(`Gamepad connected: ${e.gamepad.id}`);
});
window.addEventListener("gamepaddisconnected", (e) => {
console.log(`Gamepad disconnected: ${e.gamepad.id}`);
});
// Poll gamepad state each frame
function pollGamepads() {
const gamepads = navigator.getGamepads();
for (const gp of gamepads) {
if (!gp) continue;
// Read analog sticks (axes)
const leftStickX = gp.axes[0]; // -1 (left) to 1 (right)
const leftStickY = gp.axes[1]; // -1 (up) to 1 (down)
// Read buttons
if (gp.buttons[0].pressed) {
// A button / Cross -- jump
player.jump();
}
if (gp.buttons[7].value > 0.1) {
// Right trigger -- accelerate (analog pressure)
player.accelerate(gp.buttons[7].value);
}
}
requestAnimationFrame(pollGamepads);
}
requestAnimationFrame(pollGamepads);
IndexedDB API
What It Is
IndexedDB is a low-level, asynchronous, transactional, client-side database built into the browser. It stores significant amounts of structured data (including files and blobs) using key-indexed object stores, and supports indexes for high-performance queries.
Why It Matters for Games
- Save game state: Persist player progress, inventory, character stats, and level completion across sessions.
- Cache assets locally: Store textures, audio files, level data, and other assets to reduce network requests and enable offline play.
- Large storage capacity: Handles far more data than
localStorage(which caps at ~5 MB). - Non-blocking: Asynchronous operations keep the game loop running smoothly during save/load operations.
- Transactional: Atomic read/write operations prevent data corruption during saves.
Key Interfaces
| Interface | Purpose | Game Use Case |
|-----------|---------|---------------|
| indexedDB.open() | Open or create a database | Initialize the game database on startup |
| IDBDatabase | Database connection | Manage the connection lifetime |
| IDBTransaction | Scope and access control for reads/writes | Atomic save-game operations |
| IDBObjectStore | Primary data container | Store player profiles, level data, settings |
| IDBIndex | Secondary lookup keys | Query items by type, rarity, or other properties |
| IDBCursor | Iterate over records | Batch operations on game data |
| IDBKeyRange | Define key ranges for queries | Fetch scores within a range, recent save slots |
| IDBRequest | Async operation handle | Manage callbacks for all database operations |
Code Example
// Open (or create) the game database
const request = indexedDB.open("MyGameDB", 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create an object store for save data
const saveStore = db.createObjectStore("saves", { keyPath: "slotId" });
saveStore.createIndex("timestamp", "timestamp");
};
request.onsuccess = (event) => {
const db = event.target.result;
// Save game state
function saveGame(slot, gameState) {
const tx = db.transaction("saves", "readwrite");
const store = tx.objectStore("saves");
store.put({
slotId: slot,
timestamp: Date.now(),
playerHealth: gameState.health,
playerPosition: gameState.position,
inventory: gameState.inventory,
});
}
// Load game state
function loadGame(slot) {
return new Promise((resolve, reject) => {
const tx = db.transaction("saves", "readonly");
const store = tx.objectStore("saves");
const req = store.get(slot);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
};
JavaScript
What It Is
JavaScript is a lightweight, dynamically typed, prototype-based programming language with first-class functions. It is the scripting language of the web and the foundational language for all browser-based game logic, supporting imperative, functional, and object-oriented paradigms.
Why It Matters for Games
- Runtime environment: JavaScript is the language in which browser game logic executes.
- Event-driven architecture: Native event handling supports input, timers, and async resource loading.
- First-class functions: Callbacks and closures enable patterns like game loops, event handlers, behavior trees, and state machines.
- Dynamic objects: Runtime object creation and modification supports entity-component systems and data-driven designs.
- Modern class syntax: ES6+ classes provide clean inheritance hierarchies for game entities.
- Async/await: Clean asynchronous control flow for asset loading, server communication, and scene transitions.
- Garbage collection: Automatic memory management (though awareness of GC pauses is important for smooth frame rates).
Key Language Features for Games
| Feature | Game Application |
|---------|------------------|
| Classes and inheritance | Entity hierarchies (GameObject, Player, Enemy) |
| Closures | Encapsulated state in callbacks and event handlers |
| requestAnimationFrame | The core game loop driver |
| Promises / async-await | Asset loading, server calls, scene transitions |
| Destructuring and spread | Clean configuration and state passing |
| Map and Set | Entity lookup tables, unique ID tracking, collision sets |
| Template literals | Debug output, dynamic text rendering |
| Modules (import/export) | Organize game code into systems and components |
Code Example
// ES6+ game entity pattern
class GameObject {
constructor(x, y) {
this.x = x;
this.y = y;
this.active = true;
}
update(dt) { /* override in subclasses */ }
render(ctx) { /* override in subclasses */ }
}
class Player extends GameObject {
constructor(x, y) {
super(x, y);
this.health = 100;
this.speed = 200;
}
update(dt) {
if (input.left) this.x -= this.speed * dt;
if (input.right) this.x += this.speed * dt;
}
render(ctx) {
ctx.fillStyle = "blue";
ctx.fillRect(this.x, this.y, 32, 32);
}
}
// Game loop using requestAnimationFrame
let lastTime = 0;
function gameLoop(timestamp) {
const dt = (timestamp - lastTime) / 1000;
lastTime = timestamp;
for (const entity of entities) {
entity.update(dt);
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const entity of entities) {
entity.render(ctx);
}
requestAnimationFrame(gameLoop);
}
requestAnimationFrame(gameLoop);
Pointer Lock API
What It Is
The Pointer Lock API (formerly Mouse Lock API) provides access to raw mouse movement deltas rather than absolute cursor positions. It locks mouse events to a single element, removes cursor movement boundaries, and hides the cursor -- essential for first-person camera controls and similar mechanics.
Why It Matters for Games
- First-person camera control: Move the camera by physically moving the mouse with no screen-edge limits.
- No cursor distraction: The cursor is hidden, creating immersion.
- Persistent lock: Once engaged, movement data flows continuously regardless of mouse button state.
- Raw input option: The
unadjustedMovementflag disables OS-level mouse acceleration for consistent aim in competitive games. - Frees mouse buttons: With movement handled by deltas alone, clicks can be mapped to game actions (shoot, interact).
Key Interfaces and Methods
| API | Description |
|-----|-------------|
| element.requestPointerLock(options?) | Locks the pointer to the element. Returns a Promise. |
| document.exitPointerLock() | Releases the pointer lock. |
| document.pointerLockElement | The element currently holding the lock, or null. |
| MouseEvent.movementX | Horizontal delta since the last mousemove event. |
| MouseEvent.movementY | Vertical delta since the last mousemove event. |
| pointerlockchange event | Fired when lock state changes. |
| pointerlockerror event | Fired if locking or unlocking fails. |
Code Example
const canvas = document.getElementById("game");
// Request pointer lock on click (user gesture required)
canvas.addEventListener("click", async () => {
if (!document.pointerLockElement) {
await canvas.requestPointerLock({
unadjustedMovement: true, // raw input, no OS acceleration
});
}
});
// Respond to lock state changes
document.addEventListener("pointerlockchange", () => {
if (document.pointerLockElement === canvas) {
document.addEventListener("mousemove", handleMouseMove);
} else {
document.removeEventListener("mousemove", handleMouseMove);
}
});
// Use movement deltas for camera rotation
const sensitivity = 0.002;
function handleMouseMove(e) {
camera.yaw += e.movementX * sensitivity;
camera.pitch += e.movementY * sensitivity;
camera.pitch = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, camera.pitch));
}
Notes
- Pointer lock can only be requested in response to a user gesture (click, key press).
- Users can exit at any time with the Escape key.
- Sandboxed iframes need the
allow-pointer-lockattribute.
SVG (Scalable Vector Graphics)
What It Is
SVG is an XML-based markup language for describing two-dimensional vector graphics. Unlike raster formats (PNG, JPEG), SVG images scale to any resolution without quality loss. SVG integrates with CSS, the DOM, and JavaScript, making elements scriptable and interactive.
Why It Matters for Games
- Resolution independence: A single SVG asset looks crisp on any screen size or pixel density -- ideal for responsive game UIs.
- Lightweight: Text-based and compressible, reducing download sizes for UI art and icons.
- Scriptable via the DOM: SVG elements can be created, modified, and animated with JavaScript in real time.
- CSS styling: SVG shapes accept CSS rules for fill, stroke, opacity, transforms, filters, and animations.
- Built-in animation: SMIL animation elements (
<animate>,<animateTransform>,<animateMotion>) for declarative motion. - Filters and effects: Gaussian blur, drop shadows, color matrices, and blend modes through SVG filter primitives.
Key Elements
| Element | Game Use Case |
|---------|---------------|
| <rect> | Health bars, UI panels, platforms |
| <circle>, <ellipse> | Targets, particles, indicators |
| <path> | Complex vector art, custom shapes |
| <polygon>, <polyline> | Grid overlays, wireframe elements |
| <g> | Group elements for collective transforms |
| <defs>, <use>, <symbol> | Reusable sprite definitions |
| <text>, <tspan> | Score displays, labels, dialog |
| <filter> | Blur, shadow, and color effects |
| <clipPath>, <mask> | Viewport clipping, reveal effects |
| <linearGradient>, <radialGradient> | Shading and depth effects |
| <animate>, <animateTransform> | Declarative UI animations |
Code Example
<!-- A simple SVG health bar -->
<svg width="220" height="30" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="healthGrad" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="limegreen" />
<stop offset="100%" stop-color="green" />
</linearGradient>
</defs>
<!-- Background -->
<rect x="1" y="1" width="218" height="28" rx="5" fill="#333" stroke="#fff" stroke-width="1" />
<!-- Health fill (width controlled via JS) -->
<rect id="health-fill" x="3" y="3" width="160" height="24" rx="4" fill="url(#healthGrad)">
<animate attributeName="width" from="214" to="60" dur="3s" fill="freeze" />
</rect>
</svg>
// Update health bar programmatically
function setHealth(percent) {
const maxWidth = 214;
document.getElementById("health-fill")
.setAttribute("width", maxWidth * (percent / 100));
}
Typed Arrays
What They Are
Typed Arrays are array-like views over raw binary data buffers (ArrayBuffer). Unlike regular JavaScript arrays, each typed array has a fixed element type and size, providing predictable memory layout and efficient data access. There is no single TypedArray constructor; instead, specific constructors like Float32Array, Uint8Array, and Uint16Array are used.
Why They Matter for Games
- WebGL vertex and index buffers: WebGL methods accept typed arrays directly for positions, normals, texture coordinates, colors, and indices.
- Web Audio buffers: Audio sample data is stored and manipulated as
Float32Array. - Binary asset loading: Parse bin