Webworker canvas context issue


I have been trying to recreate / understand using webworkers with three.js, and have been trying to recreate the three.js example https://threejs.org/examples/webgl_worker_offscreencanvas.html

This is pretty much a learning exercise so is mainly a copy and play exercise, but I have used some minor differences such as using setAnimationLoop rather than requestAnimationFrame(not sure if that makes a difference).

The issue I am having is that the context of my canvas element that is set through the webworker is null when inside three.js WebGLAnimation start function.

I have a git hub with all the code. https://github.com/sirBassetDeHound/webWorkerThreeJs

Any ideas that could be offered would be appreciated as I am not sure why it is happening.

Thank you

Because of the following line, WebGLRenderer.setAnimationLoop() is not supported in workers.

window is undefined and hence no context is set.

Took me a while to get back to being able to have a look at this.

Thank you very much for answering.

I assume that this is as the docs say,
due to the context in which the worker runs.

Changing the section you mentioned to:

typeof window !== ‘undefined’ ? animation.setContext( window ) : animation.setContext( self );

And it works.

At this stage though I have no idea of the repercussions of this or if it is actually working properly :grin:

Updated: There are ways to name webworkers, so would it not be possible to pass this reference to the worker context into the THREE.js constructor so that is is aware of the context in which it is being run?

I’m not sure I understand what you mean. Can you share some demo code?

I have updated the github example I was playing with, the last commit should show the changes better than I can explain them here:

but in short when creating a new webworker
var worker = new Worker( ‘./worker.js’, { name : “threejsWorker” } );

and then when you can check what context self is set to using self.name inside three.js
self.name = threejsWorker

This way you know that the context is the correct one

This way I am thinking if you create a new instance of three.js and pass in a reference to the context you wish to use, either empty for the window or a name for a specific context. The use of self becomes more of a targeted approach rather than a fallback to not having the window object.

Again this is not something I have really explored, and is more or a thought.

@mrdoob Apparently WebGLRenderer.setAnimationLoop() does not support a usage in web workers. Especially this line is problematic. How important/urgent is a fix from your point of view? Or maybe a note in the docs that web workers are not supported is already sufficient…

But this example runs inside a web worker…

I don’t understand what is it that doesn’t work.

It seems the example does not use WebGLRenderer.setAnimationLoop().

1 Like