Multiple Materials for a Single Mesh
Learn how to add different materials to the same mesh.
We'll cover the following...
Add different materials to a single mesh
When creating THREE.Mesh
, we’ve used a single material. It is also possible to define a specific material for each of the faces of a geometry. For instance, if we have a cube that has 12 faces (remember, Three.js works with triangles), we can assign a different material (for example, with a different color) to each side of the cube. Doing this is straightforward, as shown in the following piece of code:
const mat1 = new THREE.MeshBasicMaterial({ color: 0x777777})const mat2 = new THREE.MeshBasicMaterial({ color: 0xff0000})const mat3 = new THREE.MeshBasicMaterial({ color: 0x00ff00})const mat4 = new THREE.MeshBasicMaterial({ color: 0x0000ff})const mat5 = new THREE.MeshBasicMaterial({ color: 0x66aaff})const mat6 = new THREE.MeshBasicMaterial({ color: 0xffaa66})const matArray = [mat1, mat2, mat3, mat4, mat5, mat6]const cubeGeom = new THREE.BoxGeometry(1, 1, 1, 10, 10, 10)const cubeMesh = new THREE.Mesh(cubeGeom, material)
We create an array, named matArray
(line 7), to hold all the materials and use that array to create THREE.Mesh
. What we might notice is that we only create six materials (lines 1–6), even though we’ve got 12 faces.
To understand how this works, we have to look at how Three.js assigns a material to a ...