Skip to content
jshacks.dev
Performance

Use OffscreenCanvas in worker

Transfer control of a canvas to a Web Worker with transferControlToOffscreen so heavy drawing runs off the main thread and the UI stays responsive.

1 min read
Summarize in AI

Drawing thousands of shapes on a canvas can block clicks and scrolling. With OffscreenCanvas the drawing happens in a worker.

main.jsJavaScript
const canvas = document.querySelector('canvas');
const offscreen = canvas.transferControlToOffscreen();

const worker = new Worker('draw-worker.js');
worker.postMessage({ canvas: offscreen }, [offscreen]);
draw-worker.jsJavaScript
self.onmessage = ({ data }) => {
  const ctx = data.canvas.getContext('2d');
  let x = 0;

  function frame() {
    ctx.clearRect(0, 0, data.canvas.width, data.canvas.height);
    ctx.fillRect(x % data.canvas.width, 40, 30, 30);
    x += 2;
    requestAnimationFrame(frame);
  }
  frame();
};
Text
(a square slides across the canvas while the page stays responsive)

transferControlToOffscreen() hands the canvas to the worker. Passing it in the transfer list moves it instead of copying it, and after that the main thread can no longer draw on it, though it stays in the page and shows the result.

requestAnimationFrame is available inside dedicated workers in current browsers, and it syncs to the display of the page that owns the canvas. Debugging is harder because DOM access is not available in the worker. Use it for charts, games and image processing; a simple static drawing does not need it. See OffscreenCanvas.

Also inBrowser
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.