3

I am learning OOP while using Three.js. I know, a hard way to do it. So i created a box in the scene. Now i want to change color of one face of that cube.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.set(5, 5, 10);

var geo = new THREE.BoxGeometry(5,2,5);
var mat = new THREE.MeshBasicMaterial({color:0xff0ff0, side:THREE.DoubleSide});

var mesh = new THREE.Mesh( geo, mat);
scene.add(mesh);

//Right there i want to chance color of the face. Its not working
mesh.geometry.faces[5].color.setHex( 0xffffff ); 

var edge = new THREE.WireframeHelper( mesh, 0x00ff00 );
scene.add(edge);

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
renderer.render(scene, camera);

EDIT: the reason it did not work for me was the color i used 0xffffff. This program will work unless color is 0xffffff.

  • Possible duplicate of [How to change face color in Three.js](https://stackoverflow.com/questions/11252592/how-to-change-face-color-in-three-js) – Damjan Pavlica Aug 01 '19 at 12:10

1 Answers1

4

In your case, if you want to change the color of one face of the cube, you will need to specify vertexColors in your material.

var geo = new THREE.BoxGeometry( 5, 2, 5 );

var mat = new THREE.MeshBasicMaterial( { color:0xff0ff0, vertexColors: THREE.FaceColors } );

var mesh = new THREE.Mesh( geo, mat );

mesh.geometry.faces[ 5 ].color.setHex( 0x00ffff ); 

The rendered face color will be the specified face color tinted by the material color.

If you change a face color after the mesh has been rendered at least once, you will have to set:

mesh.geometry.colorsNeedUpdate = true;

three.js r.80

WestLangley
  • 102,557
  • 10
  • 276
  • 276
  • @jj kk I made a [jsfiddle](http://jsfiddle.net/steveow/L825x65y/). West Langley's suggestion seems to work but (strangely) it only paints half of a face (i.e. one triangle). To get a whole face you can apply the `color.setHex` operation again to the appropriate index which in your case is '4', thus: `mesh.geometry.faces[ 4 ].color.setHex( 0x00ffff );` – steveOw Sep 12 '16 at 19:45
  • @WestLangley see my update and take a look at my next question [here](http://stackoverflow.com/questions/39456677/raycasting-hard-faces-of-a-mesh-three-js) –  Sep 12 '16 at 20:26
  • 1
    It changed just one half of the face. I needed to change two faces to get desired effect. – Damjan Pavlica Aug 01 '19 at 12:08