Bash.tv → GitHub → itch.io

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

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).