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.
Drawing thousands of shapes on a canvas can block clicks and scrolling. With OffscreenCanvas the drawing happens in a worker.
const canvas = document.querySelector('canvas');
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker('draw-worker.js');
worker.postMessage({ canvas: offscreen }, [offscreen]);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();
};(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.