OffscreenCanvas API example
OffscreenCanvas API example. transferControlToOffscreen() moves canvas painting off the main thread so the page stays responsive.
The problem
canvas.getContext("2d") paints on the same thread as your JavaScript. A busy loop stalls the
frames. The page looks frozen because it is.
The method
new OffscreenCanvas() is a bitmap the DOM does not own.
transferControlToOffscreen() hands a visible <canvas> to a worker. After that
transfer, getContext() on the element throws. The placeholder stays. The worker paints.
What to do
- Run
getContext("2d"). Block the main thread. The grid and the clock hitch. - Run
transferControlToOffscreen(). Block again. The clock hitches. The grid does not.
OffscreenCanvas
The constructor exists without a tag. transferControlToOffscreen is a method on
HTMLCanvasElement. A worker is how the paint leaves this thread.
typeof OffscreenCanvas
typeof HTMLCanvasElement.prototype.transferControlToOffscreen
canvas.getContext("2d")
This is an HTMLCanvasElement context. Animation frames share the main thread with the clock and
with the block.
const ctx = canvas.getContext("2d")
requestAnimationFrame(paint)
new OffscreenCanvas()
No placeholder. You draw, then transferToImageBitmap() and blit. Still this thread, unless you
construct it inside a worker. This lab blits one still.
const offscreen = new OffscreenCanvas(width, height)
const ctx = offscreen.getContext("2d")
const bitmap = offscreen.transferToImageBitmap()
visible.drawImage(bitmap, 0, 0)
transferControlToOffscreen()
If the canvas already has a context, this throws. The lab mints a new element, transfers it, and posts the
OffscreenCanvas to a worker. The worker calls getContext("2d").
const offscreen = canvas.transferControlToOffscreen()
worker.postMessage({ canvas: offscreen }, [offscreen])