DevLost

A developer lost in the mountains

Tip: how to dinamically update a texture on a mesh in three.js

Sometimes there is the need to change the texture of a mesh at run time; for instance to change aspect of a virtual character, to create some light effects and so on.
In the code snippet below, function loadNewTexture accept the url of the new image for the texture to create a new image object. In the onload event of the image, it is drawed on the texture assigned to the material of the mesh.

Do not forget to set "needsUpdate property of the mesh to true at the end.



MyObject.prototype.loadNewTexture = function (src) {
    var that = this;
    var textureImg = new Image();
    textureImg.src = src;
    textureImg.onload = function () {
        var ctx = that.mesh.material.map.image.getContext('2d');
        ctx.drawImage(textureImg, 0, 0, textureImg.width, textureImg.height, 
      0, 0, textureImg.width, textureImg.height);
        that.mesh.material.map.needsUpdate = true;
    };
}
Loading