How to use the latest version to achieve the older version of the `vertexColors: THREE.FaceColors` effect

Here is the code snippet of the older version:

  var geometry = new THREE.BoxGeometry(200, 200, 200);

  for (var i = 0; i < geometry.faces.length; i += 2) {

    var hex = Math.random() * 0xffffff;
    geometry.faces[i].color.setHex(hex);
    geometry.faces[i + 1].color.setHex(hex);

  }

  var material = new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, overdraw: 0.5 });

  cube = new THREE.Mesh(geometry, material);
  cube.position.y = 150;
  scene.add(cube);

How do I achieve that effect with the latest version of three.js

Do it like so: three.js dev template - module - JSFiddle - Code Playground

Keep in mind that working with BufferGeometry is faster than the previous approach because way less object allocation happens.

let geometry = new THREE.BoxGeometry();
geometry = geometry.toNonIndexed();

const positionAttribute = geometry.getAttribute('position');

const color = new THREE.Color();
const colors = [];

for (let i = 0; i < positionAttribute.count; i += 6) {

  color.setHex(Math.random() * 0xffffff);
  
  // face one

  colors.push(color.r, color.g, color.b);
  colors.push(color.r, color.g, color.b);
  colors.push(color.r, color.g, color.b);
  
  // face two

  colors.push(color.r, color.g, color.b);
  colors.push(color.r, color.g, color.b);
  colors.push(color.r, color.g, color.b);

}

const colorAttribute = new THREE.Float32BufferAttribute(colors, 3);
geometry.setAttribute('color', colorAttribute);

const material = new THREE.MeshBasicMaterial({vertexColors: true});
3 Likes

@Mugen87 thank you very much, it worked

@Mugen87 Could you help me to analyze this question?

https://discourse.threejs.org/t/how-to-color-the-face-on-the-3d-file-model-and-disable-color-interpolation/52831

thank you