Are web workers allowed to access a canvas object?
Newer browsers support OffscreenCanvas (see the browser compatibility in that doc), which is a canvas 2d context that runs in web workers, but automatically paints to the main thread.
The following is the basic example from that MDN doc.
In the main thread, create an OffscreenCanvas, then send it to a worker:
var htmlCanvas = document.getElementById("canvas");
var offscreen = htmlCanvas.transferControlToOffscreen();
var worker = new Worker("offscreencanvas.js");
worker.postMessage({canvas: offscreen}, [offscreen]);
In the worker thread, use the offscreen canvas reference to create a context like you would normally do on the main thread, and perform any drawing commands that you want:
onmessage = function(evt) {
const canvas = evt.data.canvas;
const gl = canvas.getContext("webgl");
function render(time) {
// ... some drawing using the gl context ...
requestAnimationFrame(render);
}
requestAnimationFrame(render);
};
(The requestAnimationFrame API exists inside the worker.)