-1

I know about [HTMLCanvasElement trransferControlToOffscreen()], this works well.

But I need several Canvases for compositing operations.

Is it possible to create canvas inside a worker without pointing to a document?

something like this:

const myOtherCanvas = new Canvas();
1
  • 1
    In case this doesn't get reopened: OffscreenCanvas is also a constructor, so you can do new OffscreenCanvas(width, height) directly in a worker context. Commented Jul 16 at 23:23

1 Answer 1

1

OffscreenCanvas(width, height) is also a constructor, so you can also call it directly, even in a Worker where no DOM is accessible:

const workerScript = `
const canvas = new OffscreenCanvas(300, 300);
const ctx = canvas.getContext('2d');
ctx.fillStyle = "red";
ctx.roundRect(20, 20, 280, 280, 20);
ctx.fill();
canvas.convertToBlob().then((blob) => postMessage(blob));
`;
const workerURL = URL.createObjectURL(new Blob([workerScript], { type: "text/javascript" }));
const worker = new Worker(workerURL);
worker.onmessage = ({ data }) => {
  const img = new Image();
  img.src = URL.createObjectURL(data);
  document.body.append(img);
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.