Reattach the canvas context after using transferControlToOffscreen?

Viewed 1830

I'm playing about with a project at the moment where I have multiple simulations running in multiple web workers.

When I need to view the current state of the simulation I use transferControlToOffscreen on a canvas element in the main thread and pass the handle into a webworker.

The problem is the next time I try to use transferControlToOffscreen or just pass the existing handle into a different web worker the browser complains that I can't reclone the canvas.

An OffscreenCanvas could not be cloned because it was detached

Is there a function I need to call to reattach the canvas before using transferControlToOffscreen again?


Edit: It also seems like I can't pass the offscreenCanvas between the workers using a MessageChannel.

Is my only option to nullify the handle to the canvas is WorkerA, replace the current canvas (in the main thread) with a new one (Maybe cloned) and then send a new offscreenCanvas to worker B?

2 Answers

So it turns out that the only solution to this was cloning the canvas, replacing it in the DOM with its own clone, and then using transferControlToOffscreen on the clone

I found that this is occurred when invoking worker.postMessage with the offscreen variable directly (worker.postMessage({canvas: offscreen}, offscreen)) and is fixed by just turning the transfer variable into an array: worker.postMessage({canvas: offscreen}, [offscreen]).

Related