A colorful triangle

Here’s a triangle whose vertices are each assigned its own color:

A colorful triangle

These colors are blended across the triangle’s interior. The code is similar to that of the uni-colored triangle we met previously.

function makeTriangle() {
  let geom = new THREE.Geometry();
  let a = new THREE.Vector3(0, 0, 0);
  let b = new THREE.Vector3(4, 0, 0);
  let c = new THREE.Vector3(0, 8, 0);
  geom.vertices.push(a, b, c);
  let face = new THREE.Face3(0, 1, 2);
  geom.faces.push(face);
  let red = new THREE.Color(1, 0, 0);
  let green = new THREE.Color(0, 1, 0);
  let blue = new THREE.Color(0, 0, 1);
  face.vertexColors.push(red, green, blue);
  let args = {vertexColors: THREE.VertexColors, side: THREE.DoubleSide};
  let mat = new THREE.MeshBasicMaterial(args);
  let mesh = new THREE.Mesh(geom, mat);
  return mesh;
}

This code constructs several colors (red, green, and blue) by calling new THREE.Color(r, g, b). Here each of the three arguments is a number in the range from 0 to 1, indicating the brightness of its color component. The sequence of colors are pushed into the array face.vertexColor, one per vertex. In this way, the colors are associated with the face’s vertices; in turn, the face belongs to the geometry. This is a simple example in which geometry and appearance are interdependent. The material object mat is told this through the vertexColors argument with which it gets constructed.