首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >three.js:将外部纹理应用于glTF

three.js:将外部纹理应用于glTF
EN

Stack Overflow用户
提问于 2021-02-27 22:27:22
回答 1查看 501关注 0票数 0

我有两个文件:"model.gltf“和"texture.jpeg”。我想将纹理文件应用到模型中,并使用three.js渲染它,但经过3天的连续研究和数以百计的尝试,我就是无法让它正常工作。我在场景中设置当前对象的方法:

代码语言:javascript
运行
复制
/**
 * SET method: Sets object in the scene (deleting previous one)
 * 
 * @author Anton Pernisch 
 * @param {string} modelPath - Path to object in glTF format
 * @param {string} texturePath - Path to texture
 * @returns {boolean}
 * 
 * @todo Texture
 */
SET_Object: function(modelPath, texturePath) {
    // Clear out the scene
    for (var i = this.prodconf3_scene.children.length - 1; i >= 0; i--) { 
        obj = this.prodconf3_scene.children[i];
        this.prodconf3_scene.remove(obj); 
    }

    const modelLoader = new THREE.GLTFLoader();

    modelLoader.load(modelPath, (gltf) => {
        // HERE? apply texture from texturePath to this gltf

        this.prodconf3_obj = gltf.scene;
        this.prodconf3_scene.add(this.prodconf3_obj);
    });
    
    return true;
}

这段代码导入glTF很好,只是它是黑色的。最终,我能够将.jpeg纹理应用到这个模型中,但只能算是一种。这是我能得到的最好的结果:

这里

这是通过这种方法实现的:

代码语言:javascript
运行
复制
/**
 * SET method: Sets current object to scene (deleting previous one)
 * 
 * @author Anton Pernisch 
 * @param {string} modelPath - Path to object in glTF format
 * @param {string} texturePath - Path to texture
 * @returns {boolean}
 * 
 * @todo Texture
 */
SET_Object: function(modelPath, texturePath) {
    // Clear out the scene
    for (var i = this.prodconf3_scene.children.length - 1; i >=0 ; i--) { 
        obj = this.prodconf3_scene.children[i];
        this.prodconf3_scene.remove(obj); 
    }

    const modelLoader = new THREE.GLTFLoader();
    const textureLoader = new THREE.TextureLoader();

    modelLoader.load(modelPath, (gltf) => {
        var model = gltf.scene;
        model.traverse((o) => {
            if (o.isMesh) {
                o.material = new THREE.MeshBasicMaterial({map: textureLoader.load(texturePath)});
            }
        });

        this.prodconf3_obj = model;
        this.prodconf3_scene.add(this.prodconf3_obj);
    });
    
    return true;
}

我也尝试过用TextureLoader load方法创建纹理,然后用

来自

函数。这根本不起作用,我得到了

未捕获的中心:无法读取未定义的属性“TypeError”

错误(我不确定是否使用

中的第一个参数

tho)。

所以,我的问题是,什么是正确的和更新的方法,以正确地将纹理应用于three.js中的glTF?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-01 06:31:44

这对我来说很好,但我想知道我们是否应该传递一个对已经加载的纹理的引用。

不是异步的,所以我们必须在回调中更新材料。

活生生的例子

..。

代码语言:javascript
运行
复制
model.traverse((o) => {
    if (o.isMesh) {
        o.material = new THREE.MeshBasicMaterial();

        textureLoader.load(texturePath, texture => {
          o.material.map = texture;
          o.material.needsUpdate = true;
        });
    }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66399793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档