Skip to content
Advertisement

How to use PixiJS in web worker

I need to display a quite complex 2D shape in a canvas using PixiJS and to do so I’d like to create and define all graphic elements in a separate thread (web worker) to not block the rest of the UI.

The problem is that when I import PixiJS in the web worker file like this

importScripts('https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.2/pixi.js');

it gives me an error because it accesses DOM elements (like window and document) and this is not allowed in web workers. How can I solve this?

This is the error:

Uncaught ReferenceError: window is not defined
at Object.179../Math.sign (Object.assign.js:3)
at s (_prelude.js:1)
at _prelude.js:1
at Object.<anonymous> (WebGLPrepare.js:101)
at Object.187../accessibility (index.js:44)
at s (_prelude.js:1)
at e (_prelude.js:1)
at _prelude.js:1
at _prelude.js:1
at _prelude.js:1

Advertisement

Answer

Well I guess you cannot. Webworkers have their own DedicatedWorkerGlobalScope with no access to the DOM, window, etc. If you have heavy computations, for instance to calculate animations, all you can do is let the webworker do the number crunching and the main thread do the rendering.

The Worker and the main thread cannot share objects. Even if the following explanation is not 100% technically correct, you can imagine that if you:

var obj = { a: { b: 100 } };
worker.postMessage(obj);

It will be more like:

                   //really dirty object clone here
worker.postMessage(JSON.parse(JSON.stringify(obj)));

With that I want to point out, that you cannot share objects with the worker and vice verca.

Find a tecnically correct explaintion here:

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Transferring_data_to_and_from_workers_further_details

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement