Skip to content

Web Workers

Olivier Biot edited this page Nov 13, 2026 · 1 revision

Web Workers

A Web Worker runs JavaScript on its own thread, away from the page. melonJS can draw from one, onto a canvas the page hands over as an OffscreenCanvas, so the page's own thread stays free.

This needs melonJS 20.14 or later, and is experimental. See Platforms for the other platforms.

Drawing from a worker

The page gives the worker control of its canvas:

// page
const canvas = document.querySelector("canvas");
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker(new URL("./game-worker.js", import.meta.url), { type: "module" });
worker.postMessage({ canvas: offscreen }, [offscreen]);

The worker hands it to the application:

// game-worker.js
import { Application, video } from "melonjs";

self.onmessage = async ({ data }) => {
    const app = new Application(data.canvas.width, data.canvas.height, {
        canvas: data.canvas,
        renderer: video.AUTO,
        scale: 1,
    });
    await app.init();
    // load assets and start the game as usual
};

What a worker doesn't have

A worker has no page, and fewer web APIs than one:

  • No input of its own. Pointer and keyboard events happen on the page, so the game in the worker doesn't receive them.
  • No sound. A worker has no Audio or AudioContext: play sound from the page.
  • No Image. melonJS loads PNG and JPEG images with fetch and createImageBitmap, which a worker has, so those work. SVG images go through Image, so they don't: use PNG.
  • Size: there is no page to fit, so set the size yourself, as above, with scale: 1.
  • Tiled maps must be JSON (.tmj and .tsj): XML needs DOMParser, which workers don't have. The video and script asset types fail.

So a worker suits drawing that runs on its own: an animated scene, a preview, a background. A game the player plays still needs its input and sound on the page.

See also

Clone this wiki locally