How can I preload textures with Three.js?

孤人 提交于 2019-12-11 01:36:42

问题


I am using THREE.TextureLoader() to preload the textures, but I can't seem to assign them to my shaders.

var textureLoader = new THREE.TextureLoader();
textureLoader.load('img/texture.jpg', function(){
    assetsLoadedCount++;
});

In another function, I check assetsLoaded to initialize my scene:

if(assetsLoadedCount == totalAssetsCount)
{
    // Create a sphere:
    var sphere = new THREE.Mesh(
        new THREE.SphereGeometry(100, 10, 10),
        new THREE.MeshBasicMaterial({
            map: textureLoader
        })
    );
    scene.add(sphere);
}

But this throws the following error:

Uncaught TypeError: Cannot read property 'x' of undefined 

回答1:


Already figured it out!

Turns out the callback-function of the load()-method give the texture as a parameter. So:

var textureLoader = new THREE.TextureLoader();
textureLoader.load('img/texture.jpg', function(t){
    assetsLoadedCount++;
    loadedTexture = t;
});

further on:

if(assetsLoadedCount == totalAssetsCount)
{
    // Create a sphere:
    var sphere = new THREE.Mesh(
        new THREE.SphereGeometry(100, 10, 10),
        new THREE.MeshBasicMaterial({
            map: loadedTexture
        })
    );
    scene.add(sphere);
}



回答2:


May be the other answer worked on the older version, this is how I got it working

var textureLoader = new THREE.TextureLoader();
textureLoader.load(url);

// Add the event listener
textureLoader.addEventListener('load', function(event){

    // The actual texture is returned in the event.content
    sphere.material.map = event.content;

});


来源:https://stackoverflow.com/questions/18012361/how-can-i-preload-textures-with-three-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!