I'm using three.js for doing animations. I want to dynamically update a material of a cube mesh. Here is example:
// create cube geometry
var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....];
var geometry = new THREE.CubeGeometry(50, 50, 50,0,0,0,material1 );
var cube = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
// ...
var material2 = [new THREE.MeshBasicMaterial({color:0xFFFFFF}), ...];
cube.geometry.materials = material2;
If I use CanvasRenderer, it works. But when I change to WebGL Renderer, it throws error: Uncaught TypeError: Cannot read property 'map' of undefined
How to update the material of a cube on runtime using WebGL?
I'm using three.js for doing animations. I want to dynamically update a material of a cube mesh. Here is example:
// create cube geometry
var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....];
var geometry = new THREE.CubeGeometry(50, 50, 50,0,0,0,material1 );
var cube = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
// ...
var material2 = [new THREE.MeshBasicMaterial({color:0xFFFFFF}), ...];
cube.geometry.materials = material2;
If I use CanvasRenderer, it works. But when I change to WebGL Renderer, it throws error: Uncaught TypeError: Cannot read property 'map' of undefined
How to update the material of a cube on runtime using WebGL?
Share Improve this question edited Sep 10, 2012 at 9:56 Matthias 7,5216 gold badges57 silver badges90 bronze badges asked Jul 13, 2012 at 10:19 lptrunglptrung 491 gold badge1 silver badge4 bronze badges2 Answers
Reset to default 4With a code fragment, it is difficult to know what is causing the error, but you cannot change materials that involve the presence or not of a texture. Try keeping all of your materials of the same type. Also, you may need to set material.needsUpdate
flag to true
.
You can find more detail and examples in the Three.js wiki about how to update things with WebGLRenderer
.
https://github./mrdoob/three.js/wiki/Updates
Also, here is a fiddle that does something similar to what you appear to be trying to do: http://jsfiddle/2FZU7/51/
EDIT: fiddle updated for three.js r.58
I think the issue is that you're setting 'materials' and not 'material' on your cube.
cube.material = material2;
material.map = texture;
material.needsUpdate = true;