OffscreenCanvas & reprojecting parts of the DOM

<canvas-slot worker="./renderer.js"> hands its canvas to a worker. On each paint the main thread captures the slotted elements with captureElementImage() and transfers the ElementImage snapshots. The worker animates them with its own requestAnimationFrame.

Live clock

Button

Plain text

Drawn off the main thread.
worker fps: –
Show the code DOM drawn by a worker
  1. Put ordinary elements in the canvas element and name a worker script. Each child has a slot name. They stay DOM, so the button takes clicks.
  2. Load the element on the page. That is all the page does. The worker can post messages back (here, its frame rate).
  3. What the element does for you: hand the canvas to the worker, then send snapshots. transferControlToOffscreen() once, then on every paint event captureElementImage(el) for each element that changed, and transfer the snapshots with postMessage.
  4. The worker draws the snapshots. It owns the canvas and runs its own requestAnimationFrame. ctx.drawElementImage(img, …) works with a transferred snapshot the same way it works with an element.

While the main thread is blocked the orbit keeps moving (the worker owns the canvas), but the clock freezes: new snapshots only come from the main thread's rendering update. Try clicking the button while it orbits; drawing in the worker updates the element's geometry back on the main thread.

Reprojecting parts of the DOM

One element, drawn once, then re-used: a magnifier that follows the pointer or your finger (source-rect crops of the same snapshot), and plain <canvas> elements elsewhere on the page that copy regions of the source canvas.

A document, drawn once

Move your pointer over this, or press and drag on a touch screen. The lens redraws a crop of the same drawElementImage() snapshot at 2.5×, clipped to a circle, so it stays sharp. Text stays selectable underneath.

RegionQ3Q4
North1,2041,388
South9821,045
Show the code magnifier and mirrors
  1. One element in the canvas.
  2. Draw it once, then draw a crop of it again, bigger. The nine-argument drawElementImage(el, sx, sy, sw, sh, dx, dy, dw, dh) takes a source rectangle in canvas pixels. preserveElementGeometry keeps clicks going to the first, full-size draw.
  3. Copy regions into other canvases. A snapshot only draws into its own canvas, so the mirrors copy pixels with plain drawImage(sourceCanvas, …).
heading region
table region (live)

What works with OffscreenCanvas (live)

ResultExperimentDetail

Findings