Explaining the issue with an example. I have included a brief snippet of HTML code here to demonstrate the problem. In this scenario, I have created a simple triangle geometry as a global variable. By clicking the "Red" button, function red() is invoked to display the triangle in red color. The challenge arises when attempting to render the triangle in green by clicking the "Green" button if it has already been displayed in red.
<html>
<body>
<div id="container"></div>
<button onclick="red()">Red</button>
<button onclick="green()">Green</button>
<script src="http://threejs.org/build/three.js"></script>
<script>
//Code snippets for initialization
var w=300;
var h=300;
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(w, h);
document.getElementById('container').appendChild( renderer.domElement );
var scene = new THREE.Scene();
var light = new THREE.DirectionalLight(0xffffff);
light.position.z = 10;
scene.add(light);
var camera = new THREE.PerspectiveCamera( 20, w / h, 1, 1000 );
camera.position.z = 10;
var materials = [new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors, shininess: 0 } )];
//Creating the geometry
var shape = new THREE.Shape();
shape.moveTo( 0,0 );
shape.lineTo( 0, 1 );
shape.lineTo( 1, 0);
var geometry = new THREE.ShapeGeometry([shape]);
var obj = THREE.SceneUtils.createMultiMaterialObject(geometry, materials);
scene.add(obj);
//
function red()
{
change_color(new THREE.Color(0xff0000));
renderer.render(scene, camera);
}
//
function green()
{
change_color(new THREE.Color(0x00ff00));
renderer.render(scene, camera);
}
//
function change_color(color)
{
geometry.colorsNeedUpdate = true;
for(var i=0;i<geometry.faces.length;i++)
{
if(geometry.faces[i].vertexColors[0]==undefined)
{
geometry.faces[i].vertexColors[0]=color;
}
else
{
geometry.faces[i].vertexColors[0].copy(color);
}
if(geometry.faces[i].vertexColors[1]==undefined)
{
geometry.faces[i].vertexColors[1]=color ;
}
else
{
geometry.faces[i].vertexColors[1].copy(color);
}
if(geometry.faces[i].vertexColors[2]==undefined)
{
geometry.faces[i].vertexColors[2]=color;
}
else
{
geometry.faces[i].vertexColors[2].copy(color);
}
}
}
</script>
</body>
</html>