Menu - Top - Home - Donate to Me

Texture Examples

Back to documentation index.

Contents

Texture Loaders

A texture loader (TextureLoader) caches textures loaded and uploaded to WebGL contexts.

Sample Code for Loading Textures

Loading a single texture

The loadAndMapTexture method of TextureLoader returns a promise, which will receive either the texture loaded or an error. Loading a texture often happens asynchronously, so code that follows the loadAndMapTexture call (and its corresponding then calls) will generally run without waiting for the texture to finish loading.

In the sample code below, the variable textureURL is the URL of the texture to load.

  var loader=new H3DU.TextureLoader();
  loader.loadAndMapTexture(textureURL, scene).then(function(tex){
    // texture is loaded, the Texture object is in the "tex" parameter
    // Now create a sphere
    var mesh=H3DU.Meshes.createSphere(1);
    // Make a shape using the texture
    var shape=new H3DU.Shape(mesh).setTexture(texture);
  }, function(error){
    // an error occurred
  });

Loading multiple textures

If you need to load multiple textures, the loadAndMapTexturesAll method is much more convenient than loadAndMapTexture and also loads textures asynchronously.

In the sample code below, The variables textureURL1 and textureURL2 are URL textures.

  var loader=new H3DU.TextureLoader();
  loader.loadAndMapTexturesAll([
   textureURL1,
   textureURL2
  ], scene).then(function(res){
      // All the textures have loaded successfully,
      // read the textures from the array (they will
      // appear in the same order given in the
      // loadAndMapTexturesAll method).
      for(var i=0;i<res.length;i++){
        var texture=res[i];
        // deal with the texture (a Texture object)
      }
  }, function(res){
   // Some or all of the textures failed to load
   if(res.failures.length>0){
     // We have some failing textures
   }
   if(res.successes.length>0){
     // We have some succeeding textures
   }
  });

Demos

Back to documentation index.