Search code examples
javascriptthree.jstextures

THREE.js Add textures with Promises


I'm trying to use promises to load textures in THREE.JS but i don't know how to do it. I've seen how they work, but is there any example? I'm trying to load an pic (img.png) in a cube mesh.

I don't want to use JSON.


Solution

  • This the source code of THREE.ImageUtils.loadTexture from THREE.js:

    THREE.ImageUtils = {
    
      crossOrigin: undefined,
    
      loadTexture: function ( url, mapping, onLoad, onError ) {
    
        var loader = new THREE.ImageLoader();
        loader.crossOrigin = this.crossOrigin;
    
        var texture = new THREE.Texture( undefined, mapping );
    
        loader.load( url, function ( image ) {
    
          texture.image = image;
          texture.needsUpdate = true;
    
          if ( onLoad ) onLoad( texture );
    
        }, undefined, function ( event ) {
    
          if ( onError ) onError( event );
    
        } );
    
        texture.sourceFile = url;
    
        return texture;
    
      },
    

    So you can just wrap that up in a custom function that returns a Promise (this is ES6 syntax):

    loadTextureAsync (url, mapping) {
    
      return new Promise ((resolve, reject) => {
    
        const onLoad = (texture) => resolve (texture)
    
        const onError = (event) => reject (event)
    
        THREE.ImageUtils.loadTexture(
          url, mapping, onLoad, onError)
      })
    }