Camera Controller
A 2D camera that follows the player smoothly, zooms, shakes, stays inside the level and converts between screen and world positions.
Files: camera-controller.js (the component, no dependencies) and camera-controller.test.mjs (6 tests).
Copy camera-controller.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createCamera } from "./camera-controller.js";
const cam = createCamera({ width: 480, height: 270, bounds: { x: 0, y: 0, w: level.w, h: level.h }, smooth: 8, deadzone: { w: 60, h: 40 } });
cam.follow(player);
function frame(dt) {
cam.update(dt);
ctx.save(); cam.apply(ctx); drawWorld(); ctx.restore(); // HUD after restore stays put
}
cam.shake(0.5); // on a big hit
const world = cam.toWorld(input.pointer.x, input.pointer.y);
API
createCamera({ width, height, x, y, zoom, smooth, deadzone, bounds, lookAhead, maxShake, shakeScale }) → camcam.follow(target, { offsetX, offsetY })target has x, y (and w, h to aim at its centre); null to stopcam.update(dt)move towards the target, ease zoom, decay shakecam.apply(ctx)set the canvas transform (Canvas 2D)cam.shake(amount 0..1)adds trauma; shake strength is trauma², so small hits stay smallcam.shakeScale0 turns shaking off (for players who get motion sick), 1 normalcam.zoomTo(z, seconds) / cam.zoomcam.moveTo(x, y) / cam.snap()jump instantly (new level, respawn)cam.toWorld(sx, sy) / cam.toScreen(wx, wy)cam.view → { x, y, w, h }visible world area, for skipping off-screen drawingcam.resize(width, height)
cam.x, cam.y centre of the view in world units; cam.offset → current shake offset
Engines
| Engine | Notes |
|---|---|
| Vanilla / Canvas 2D | apply(ctx). |
| PixiJS | run update(), then set world.pivot to (cam.x + offset.x, cam.y + offset.y), world.position to the screen centre and world.scale to cam.zoom. |
| Phaser | use this.cameras.main (it has follow, deadzone, shake and bounds). |
| Three.js | for 2D or top-down games, copy cam.x / cam.y into an OrthographicCamera’s position each frame. |
Tests
Node tests: follow and smoothing, deadzone, bounds, small levels centred, zoom easing, shake decay and the off switch, screen and world conversion.
Run them with node --test toolkit/components/camera-controller/ (Node 20 or newer, nothing to install).