0

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;

  }

});
Klaus Andrade
  • 33
  • 1
  • 10

1 Answers1

0

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;
...
Brakebein
  • 2,197
  • 1
  • 16
  • 21
  • This answer is incorrect. You do not need to recompile the shader by setting `material.needsUpdate = true;` to change the texture. – WestLangley Jun 29 '18 at 16:00
  • Hm, maybe I picked it up falsly. And in my code, it also works without `needsUpdate = true´, as I just tested it. But this means that other answers are also incorrect in this matter? https://stackoverflow.com/questions/16066448/three-js-texture-image-update-at-runtime – Brakebein Jul 02 '18 at 11:12
  • `needsUpdate = true` needs to be set on the new texture, or on `material.map` after the new texture is assigned. But `TextureLoader` sets the `needsUpdate` flag for you. – WestLangley Jul 02 '18 at 13:35