Responsive Layout Manager
Sizes the game canvas to any screen, from phone to desktop, portrait or landscape: keeps a fixed game resolution with letterboxing or fills the screen, stays sharp on high-density screens, keeps clear of phone notches and converts taps to game coordinates.
Files: responsive-layout.js (the component, no dependencies) and responsive-layout.test.mjs (4 tests).
Copy responsive-layout.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createLayout } from "./responsive-layout.js";
const layout = createLayout({ canvas, width: 480, height: 270, mode: "fit" }); // game coordinates stay 480 x 270
layout.onResize((l) => { if (l.portrait) showRotateHint(); });
function draw() { layout.begin(ctx); drawGame(ctx); } // sets the scale; draw in game coordinates
const p = layout.toGame(event.clientX, event.clientY);
API
createLayout({ canvas, container, width, height, mode, maxDpr, pixelArt, target, onResize }) → layoutmode “fit”: whole game visible, bars on the sides if the shape differs (default) mode “fill”: cover the screen, edges may be cut off mode “expand”: keep the height (or width) and show more of the world on wider screens; layout.width / height change pixelArt: true → whole-number scaling and no smoothing, so pixels stay squarelayout.resize()read the container size again (called on window resize and orientation change)layout.begin(ctx)set the transform for drawing in game coordinates (and clear the bars)layout.toGame(clientX, clientY) → { x, y, inside }layout.width / heightgame coordinates visible nowlayout.scale / dpr / cssWidth / cssHeight / offsetX / offsetY / portraitlayout.safe → { top, right, bottom, left } in game coordinates (from CSS env(safe-area-inset-*), for notches)layout.onResize(fn) → off / layout.destroy()computeLayout(viewW, viewH, gameW, gameH, mode, dpr, maxDpr, pixelArt)the maths alone, for tests or other engines
Put the canvas in a container that fills the screen (e.g. 100vw x 100dvh) and give the page .
Engines
| Engine | Notes |
|---|---|
| Vanilla / Canvas 2D | yes. |
| Phaser | use the Scale Manager (Phaser.Scale.FIT / ENVELOP / RESIZE); computeLayout can still help. |
| PixiJS | use computeLayout and app.renderer.resize(); set the stage scale to layout.scale. |
| Three.js | call renderer.setPixelRatio(layout.dpr) and renderer.setSize(cssWidth, cssHeight), then update camera.aspect. |
Tests
Node tests: fit, fill and expand in portrait and landscape, high-density screens and the cap, pixel-art whole numbers, tap conversion with bars, resize events, safe areas.
Run them with node --test toolkit/components/responsive-layout/ (Node 20 or newer, nothing to install).