Threejs 在运行时更改图像 [英] Threejs Change image at runtime

查看:102
本文介绍了Threejs 在运行时更改图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在展示一个 3d obj 并将纹理应用为 jpg.但是我想在单击按钮时更改此图像,这是可能的,我该怎么做?

I'm showing a 3d obj and applying the texture as jpg. but I want to change this image when I click on a button, it is possible and how could I do that?

var loader = new THREE.ImageLoader(manager);
loader.load('models/obj/dla/dla.jpg', function(image) {
    texture.image = image;
    texture.repeat.set(1,1);
    texture.needsUpdate = true;
});

// model
var loader = new THREE.OBJLoader(manager);
loader.load('models/obj/dla/dla.obj', function(object) {

  object.traverse(function(child) {

  if (child instanceof THREE.Mesh) {

    child.material.map = texture;

  }

});

推荐答案

如果您更改材质的纹理/贴图,设置 material.needsUpdate = true 很重要.

If you change the texture/map of a material, it is important to set material.needsUpdate = true.

.needsUpdate : 布尔值

.needsUpdate : Boolean

指定需要在 WebGL 级别更新材料.如果您进行了需要反映在 WebGL 中的更改,请将其设置为 true.实例化新材质时,此属性会自动设置为 true.

Specifies that the material needs to be updated at the WebGL level. Set it to true if you made changes that need to be reflected in WebGL. This property is automatically set to true when instancing a new material.

这是一些代码,我将如何实现它.我也会使用 TextureLoader 而不是 ImageLoader.

Here is some code, how I would implement it. I would also use TextureLoaderinstead of ImageLoader.

// init
var obj;
var objLoader = new THREE.OBJLoader(manager);
var textureLoader = new THREE.TextureLoader(manager);

// load model
objLoader.load('models/obj/dla/dla.obj', function(object) {

  obj = object;
  loadTexture('models/obj/dla/dla.jpg', obj)

});

// load texture
function loadTexture(path, object) {
  textureLoader.load(path, function(texture) {
    object.traverse(function(child) {

      if (child instanceof THREE.Mesh) {

        child.material.map = texture;
        child.material.needsUpdate = true;

      }

    });
  });
}

// onclick handler
function onClick() {
  loadTexture('models/obj/dla/anotherTexture.jpg', obj);
}

如果您不再使用旧纹理,您可能需要从内存中处理它.

If you don't use the old texture anymore, you might want to dispose it from memory.

...
if (child.material.map) child.material.map.dispose();

child.material.map = texture;
child.material.needsUpdate = true;
...

这篇关于Threejs 在运行时更改图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆