npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@drk4/game-engine

v4.4.0

Published

A 2D game engine for simple browser games using the HTML canvas.

Readme

@drk4/game-engine

npm version license

A small TypeScript-first 2D game engine for browser games rendered with the HTML canvas. It provides the pieces most simple games need:

  • Canvas & game loop — automatic canvas setup and a frame loop you can hook into.
  • Drawable elements — rectangles, circles, text, bitmaps, and sprites.
  • Input & events — mouse and event handling on any element.
  • Tweens — animate element properties over time.
  • Assets & sound — preload images, audio, JSON, and text, plus sound playback.
  • Sprite animation — frame-based animation from sprite sheets.
  • Collision detection — category-based collisions, with a spatial-partition mode for many elements.
  • HTML helpers — lightweight, styled UI helpers like buttons, menus, and messages.

The full API reference is in docs/README.md, and runnable examples live in examples/.

Contents

Install

# with pnpm
pnpm add @drk4/game-engine

# with npm
npm install @drk4/game-engine

Import the engine from your app code:

import * as Game from "@drk4/game-engine";

You can also import the optional stylesheet:

import "@drk4/game-engine/style.css";

The stylesheet is exported by the package and maps to the bundled dist/game_engine.css file. It provides basic styling for the engine's HTML helpers. Every class and id defined by the engine starts with Game-, for example .Game-Container, so custom game styles can avoid conflicts easily.

The engine is built on @drk4/utilities (dialogs, timers, random numbers, local storage, and more). To use those in your game, install it and import it directly:

pnpm add @drk4/utilities
import * as Utilities from "@drk4/utilities";

When your game extends the engine's classes, enable noImplicitOverride in your tsconfig.json. Overriding a method then requires the override keyword, so when a new version of the engine renames a method, the compiler reports your overrides of it (instead of keeping them as new methods that the engine never calls).

{
    "compilerOptions": {
        "noImplicitOverride": true
    }
}

Upgrading

The changes in each version are in the changelog. To update a game from v3 to v4, follow the migration guide.

Getting started

Game.init() creates the canvas, attaches it to the page, and starts the game loop. After that, create elements and add them to the canvas with Game.addElement().

This example creates a movable player, keeps it inside the canvas, updates text each frame, and uses a tween when the player is clicked.

import * as Game from "@drk4/game-engine";
import "@drk4/game-engine/style.css";

const WIDTH = 480;
const HEIGHT = 320;
const SPEED = 180; // Player movement, in pixels per second.

Game.init({ container: document.body, width: WIDTH, height: HEIGHT });

// Name the actions, and bind keys to them (the arrows or WASD).
const controls = new Game.Keyboard({
    left: ["ArrowLeft", "KeyA"],
    right: ["ArrowRight", "KeyD"],
    up: ["ArrowUp", "KeyW"],
    down: ["ArrowDown", "KeyS"],
});

const player = new Game.Rectangle({
    x: WIDTH / 2, // x/y is the center of the element.
    y: HEIGHT / 2,
    width: 32,
    height: 32,
    color: "seagreen",
});

const label = new Game.Text({
    x: 16,
    y: 16,
    text: "Move with the arrows or WASD",
    fontSize: 18,
});

Game.addElement([player, label]);

player.addEventListener("click", function () {
    new Game.Tween(player, { override: true })
        .to({ rotation: player.rotation + Math.PI * 2 }, 0.4)
        .start();
});

Game.addToGameLoop(function (deltaTime) {
    let x = 0;
    let y = 0;

    if (controls.isHeld("left")) x -= 1;
    if (controls.isHeld("right")) x += 1;
    if (controls.isHeld("up")) y -= 1;
    if (controls.isHeld("down")) y += 1;

    if (x !== 0 || y !== 0) {
        const length = Math.hypot(x, y);
        const half = player.width / 2;

        // Move at a constant speed, kept inside the canvas bounds.
        player.x = clamp(
            player.x + (x / length) * SPEED * deltaTime,
            half,
            WIDTH - half,
        );
        player.y = clamp(
            player.y + (y / length) * SPEED * deltaTime,
            half,
            HEIGHT - half,
        );
    }

    label.text = `Position: ${Math.round(player.x)}, ${Math.round(player.y)}`;
});

function clamp(value: number, min: number, max: number) {
    return Math.min(max, Math.max(min, value));
}

Loading assets

Use Preload to load images, audio, JSON, and text files. With saveGlobal: true, the loaded files are stored globally and retrieved from Game.Preload.

async function loadAssets() {
    const preload = new Game.Preload({ saveGlobal: true });

    try {
        await preload.loadManifest(
            [
                { id: "ship", path: "ship.png" },
                { id: "music", path: "music.ogg", optional: true }, // The game can run without it.
            ],
            "assets/", // Base path, prepended to every file.
        );
    } catch (error) {
        // A `Game.PreloadError`, with the files that couldn't be loaded (and aren't optional) in `failedIds`.
        console.error(error);
        return;
    }

    const ship = new Game.Bitmap({
        x: 200,
        y: 200,
        image: Game.Preload.requireImage("ship"),
    });
    Game.addElement(ship);

    // Play looping background music at half volume (`undefined` when the music couldn't be loaded).
    const music = Game.Preload.getAudio("music");

    if (music) {
        Game.Sound.play(music, { loop: true, volume: 0.5 });
    }
}

loadAssets();

loadManifest() returns a promise that resolves once every file was dealt with, or rejects with a Game.PreloadError when a file that isn't optional fails, so a missing file is an error instead of a game that starts without it. Get the files the game can't run without with requireImage(), requireAudio(), requireJson<T>() or requireText(), which throw an error naming the id when there's no such file (after loadManifest() resolved, that can only be a wrong id). Get the optional ones with getImage(), getAudio(), getJson<T>() or getText(), which return undefined for a file that wasn't loaded (get() returns any). There are also events: complete once every file was dealt with (with failedIds and loadedIds), and error for each file that fails. Their listeners are typed (see PreloadEvents).

The sounds pause while the page is hidden, like the game loop (see Game.Sound.setPauseWhenHidden()). Browsers only play audio after the player interacts with the page, so the sounds played before that (the music, when the game starts) start on the first key press, click or touch.

Sprites and animation

A Sprite animates frames from a sprite sheet. Pass { loop: false } to play an animation once; it emits an animationend event when it reaches the last frame. Add destroyOnEnd: true to destroy the sprite then (for one-shot effects).

const explosion = new Game.Sprite({
    x: 200,
    y: 200,
    image: Game.Preload.requireImage("explosion"),
    frameWidth: 40,
    frameHeight: 40,
    interval: 0.07, // Seconds between frames.
    animations: { boom: [0, 1, 2, 3, 4, 5] },
});

Game.addElement(explosion);

// Play once, then destroy itself when finished.
explosion.play("boom", { loop: false, destroyOnEnd: true });

Input and events

Add listeners to any element. The mouse events are click, mousedown, mouseup, mouseover, mouseout, and mousemove.

const button = new Game.Rectangle({
    x: 200,
    y: 200,
    width: 80,
    height: 30,
    color: "steelblue",
});

Game.addElement(button);

button.addEventListener("click", function () {
    console.log("clicked!");
});

For the keyboard, name the game's actions and bind keys to them once, with Game.Keyboard. The game code then only asks about the actions:

const controls = new Game.Keyboard({
    left: ["ArrowLeft", "KeyA"],
    right: ["ArrowRight", "KeyD"],
    fire: "Space",
});

Game.addToGameLoop(function (deltaTime) {
    if (controls.isHeld("left")) {
        player.x -= 100 * deltaTime;
    }

    // True for one update, even for a quick tap between two updates.
    if (controls.wasPressed("fire")) {
        player.fire();
    }
});

The keys are KeyboardEvent.code values, which name a key by its position on the keyboard (KeyW is where W is on a US keyboard, and where Z is on a French one), so the controls stay in place with any layout. The action names are checked by TypeScript. The keys are let go when the window loses the focus or the game loop pauses, keys typed in form fields are ignored, and the bound keys don't scroll the page (with Ctrl, Cmd or Alt held they do their default action, so the browser's shortcuts keep working). Change the keys with controls.setKeys() (for an options screen). For a game where every press is an action (a move in a turn-based game), controls.getPresses() gives the actions pressed since the last update, in order and once per press.

Removing elements

There are two ways to take an element out of the game:

  • element.destroy() destroys it. It stops colliding and its tweens stop right away, and at the end of the current frame it's taken out of its container/canvas. Destroying a container destroys its children as well. A destroyed element can't be added again.
  • container.removeChild(element), canvas.removeChild(element) or Game.removeElement(element) detach it right away. It's no longer drawn, updated or considered in the collision detection, but it stays usable, so you can add it again later (to the same or another container/canvas).
// A bullet that hit something is gone for good.
bullet.destroy();

// A paused menu is taken out, and added back later.
Game.removeElement(menu);
Game.addElement(menu);

// Restarting a level: the layer stays (it sets the drawing order), its elements are thrown away.
enemiesLayer.destroyAllChildren();

Adding an element that is already in a container/canvas moves it to the new one.

The elements are positioned by their center (x/y). To position them by an edge, set left, top, right or bottom.

Tweens

A Tween animates an element's properties over time. Durations are in seconds. Pass { override: true } to cancel any tween already running on the target, or { override: "properties" } to only take the properties this tween animates out of the target's other tweens (a move that takes over from the previous move, while a fade-in keeps going).

const tween = new Game.Tween(player, { override: true });

tween
    .to({ x: 350 }, 1) // Animate x to 350 over 1 second.
    .wait(0.5)
    .to({ y: 350 }, 1, Game.Tween.Ease.quadraticIn)
    .call(function () {
        console.log("done");
    });

tween.start();

Game loop

Run your own logic on the loop with Game.addToGameLoop(). The callback receives deltaTime, the number of seconds since the last update. By default it runs every tick; pass a delay in seconds to run on an interval.

// Every tick: move at a constant speed regardless of frame rate.
Game.addToGameLoop(function (deltaTime) {
    player.x += 50 * deltaTime;
});

// Every 2 seconds.
Game.addToGameLoop(spawnEnemy, { delay: 2 });

For a timer that belongs to an element (an attack, health regeneration), use a Game.Cooldown in the element's logic(), so it pauses with the game. It keeps to the interval whatever the frame rate is, and doesn't build up time while it waits to be used. For an interval that changes each time (a random spawn time), pass the next one to restart():

class Tower extends Game.Rectangle {
    attack = new Game.Cooldown(0.5); // Twice per second.

    constructor(args: Game.RectangleArgs) {
        super(args);
        this._has_logic = true; // Call logic() on every update.
    }

    override logic(deltaTime: number) {
        this.attack.update(deltaTime);

        const target = findTarget(this);

        if (target && this.attack.isReady()) {
            this.attack.restart();
            shoot(this, target);
        }
    }
}

By default the loop updates on every animation frame, which follows the display's refresh rate (60 times per second on most displays). To limit it, use Game.setFps(). The loop pauses while the page is hidden. To keep a long pause (a slow device, the debugger) from moving the elements a big distance at once, deltaTime is limited to 0.25 seconds (change it with Game.setMaxDeltaTime()). A loop stopped with Game.stopGameLoop() stays stopped until Game.startGameLoop() is called.

To make the game behave the same on every display, run its logic at a fixed rate with Game.setFixedTimestep(). The logic (the callbacks, tweens, logic() and collisions) then always gets the same deltaTime, as many times as the time that passed calls for, and the elements are drawn between the last two steps, so they still move smoothly at 120 or 144Hz:

Game.setFixedTimestep(1 / 60); // The logic runs 60 times per second, whatever the display.

// After moving an element to a new place at once, draw it there (instead of moving there smoothly).
player.x = START_X;
player.resetInterpolation();

What runs outside of the loop doesn't pause with it, like a setTimeout() or a timer shown in the page. For those, use game time: Game.Timeout (a timeout) and Game.Stopwatch (to measure a time, like how long a level took) run on the loop, so they pause with it.

const nextLevel = new Game.Timeout();
nextLevel.start(() => startLevel(2), 2); // After 2 seconds of game time.

const levelTime = new Game.Stopwatch();
levelTime.start();
// ...
showScore(levelTime.getTime()); // In seconds.

For anything else, listen to the loop's pause and resume events (dispatched for a hidden page and for stopGameLoop()/startGameLoop()):

Game.addEventListener("pause", () => music.pause());
Game.addEventListener("resume", () => music.resume());

To test the game's timing, stop the loop and update it by hand with Game.step(deltaTime) (see Testing).

Collision detection

Give elements a category bit flag and the categories they should collide with through collidesWith. Colliding elements receive a collision event. Only the elements added to a canvas (directly or through containers) take part in the collision detection.

const PLAYER = 1; // 0b01
const ENEMY = 2; // 0b10

player.category = PLAYER;
player.collidesWith = ENEMY;

const enemy = new Game.Rectangle({
    x: 100,
    y: 100,
    width: 20,
    height: 20,
    color: "red",
    category: ENEMY,
    collidesWith: PLAYER,
});

Game.addElement(enemy);

player.addEventListener("collision", function (data) {
    console.log("player hit", data.collidedWith);
});

The collision events come once per update, after the logic. To check two elements in the game's own logic instead (right after moving them), use overlaps(). It uses their current positions, and the same shapes as the collision detection, but not the categories:

if (player.overlaps(enemy)) {
    loseLife();
}

For a large number of elements, use the spatial-partition algorithm instead of the default algorithm, which checks every pair:

const collision = new Game.CollisionDetection.SpatialPartition({
    canvasWidth: 400,
    canvasHeight: 400,
    partitions: 10,
});

Game.init({ container: document.body, width: 400, height: 400, collision });

Testing

A game can be tested with a test runner like Vitest, in a browser-like environment (jsdom), with the helpers of @drk4/game-engine/testing (they aren't in the main entry, so they aren't in the game's bundle):

  • stubCanvasContext() gives the canvas a 2d context that does nothing (jsdom doesn't draw).
  • stubAnimationFrames() keeps the game loop from running by itself, so the game is updated with Game.step(deltaTime).
  • resetGame() leaves the engine as if it was just loaded, so a test doesn't affect the next one: the game is taken out of the page, and its game loop callbacks, tweens, held keys and preloaded files are removed.
import * as Game from "@drk4/game-engine";
import {
    resetGame,
    stubAnimationFrames,
    stubCanvasContext,
} from "@drk4/game-engine/testing";
import { afterEach, beforeEach, expect, test } from "vitest";

beforeEach(function () {
    stubCanvasContext();
    stubAnimationFrames();

    Game.init({ container: document.body, width: 400, height: 400 });
    Game.stopGameLoop();
});

afterEach(function () {
    resetGame();
});

test("a car spawns every 2 seconds", function () {
    startLevel(1);

    // Two seconds, at 60 updates per second.
    for (let a = 0; a < 120; a++) {
        Game.step(1 / 60);
    }

    expect(countCars()).toBe(1);
});

Documentation

The full API reference is available in docs/README.md.

There are also many runnable examples in the examples/ directory. Inside this repository, run pnpm run dev to browse them locally.

Release

  1. Run the checks (pnpm run format:check, pnpm run typecheck:all, pnpm run lint, pnpm test and pnpm run build), and try the examples (pnpm run dev) in the different browsers.
  2. Update the version in package.json, the CHANGELOG.md and the API reference (pnpm run docs), and commit.
  3. Tag the commit and push it (git tag vX.Y.Z and git push origin master vX.Y.Z).
  4. The release workflow stages the package on npm (with provenance), then approve it on npmjs.com to publish it.
  5. Before announcing it, check that it installs: npm can list a new version a minute before its files can be downloaded.

License

MIT