Threejs Change image at runtime

橙三吉。 提交于 2019-12-13 03:29:13

问题


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;

  }

});

回答1:


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

.needsUpdate : Boolean

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.

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;
...


来源:https://stackoverflow.com/questions/51079295/threejs-change-image-at-runtime

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