Search code examples
javascriptthree.jsweb-worker

can`t use three.js texture loader in javascript worker


I'm trying to use three.js to load the texture.

main.js:

const worker = new Worker('../workers/worker.js', {
    type: 'module'
  });

and this is the simple worker.js:

    import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
 const textureLoader = new THREE.TextureLoader();
    textureLoader.load(
      // resource URL
      'images/texture.jpg',
    
      // onLoad callback
      function ( texture ) {
        // in this example we create the material when the texture is loaded
        const material = new THREE.MeshBasicMaterial( {
          map: texture
         } );
      },
    
      // onProgress callback currently not supported
      undefined,
    
      // onError callback
      function ( err ) {
        console.error( 'An error happened.' );
      }
    );

But I get following error:

Uncaught ReferenceError: document is not defined

In my searches, I got it there is no way to access the DOM but I don't know how I can fix that, Thanks.


Solution

  • You can solve this issue by using THREE.ImageBitmapLoader instead of THREE.TextureLoader. This new type of loader has no dependency to the DOM.

    There is also an official example that demonstrate the loader. The basic usage is:

    const loader = new THREE.ImageBitmapLoader();
    loader.load( 'path/to/my/texture.png', function ( imageBitmap ) {
    
            const texture = new THREE.CanvasTexture( imageBitmap );
            const material = new THREE.MeshBasicMaterial( { map: texture } );
    
    } );