How to color the faces of a box geometry using a shader in ThreeJS
![Oscar de la Hera Gomez](https://www.delasign.com/CDN/headshots/profile.webp)
![Two flowers that represent React and ThreeJS, beneath them sits the text "Box Geometry Colored Faces Shader."](https://www.delasign.com/CDN/images/How-to-color-the-faces-of-a-box-geometry-using-a-shader-in-ThreeJS.webp)
A step by step tutorial on coloring the faces of a box geometry using a shader in ThreeJS using ReactJS.
We recommend that you clone our Open Source React-Redux Starter Project, checking out the tutorial/three-js/starter branch and carrying out the steps below. The changes can be found on the tutorial/three-js/cube-colored-faces-shader-material branch.
Box Geometry Faces & Vertices
![An illustration that demonstrates how the vertices are broken down by face on a box geometry.](https://www.delasign.com/CDN/images/Box-Geometry-Breakdown.webp)
The diagram above describes what vertex applies to what face within a box geometry and the color that we applied to each face as part of this tutorial.
Tutorial
Step One: Setup the Project
![A screenshot of Chrome showing that the orbit controls work and that the cube can now be seen from different angles and distances.](https://www.delasign.com/CDN/images/Test_2023-11-08-205052_vifb.webp)
Follow the tutorials below to learn how to create a ThreeJS project that implements a shader on a box geometry, which can be explored using Orbit Controls.
Step Two: Set the Vertex Colors
![A screenshot of VSCode showing how we created a Float32Array that holds the colors for each vertex.](https://www.delasign.com/CDN/images/Set-Vertex-Colors.webp)
Create a Float32Array array that holds the 24 colors for the cube.
If you wish to set specific colors for each vertex, consult the diagram above the tutorial.
Step Three: Set the Color Attribute
![A screenshot of VSCode showing how to set the colors as an attribute of the shader.](https://www.delasign.com/CDN/images/Set-the-Attribute.webp)
Apply the colors to the shader by setting them as an attribute using code similar to the one below.
const colorAttribute = new THREE.BufferAttribute(colors, 3); // 3 components (RGB) per vertex
geometry.setAttribute("aVertexColor", colorAttribute);
Step Four: Update Shaders
![A screenshot of VSCode showing the updated Vertex and Fragment shader.](https://www.delasign.com/CDN/images/Update-Shader_2023-11-08-222254_hncj.webp)
Update the vertex and fragment shader to work with the attribute.
Vertex Shader
Fragment Shader
Step Five: Test
![A screenshot of Chrome showing a cube with colored faces that match the colors we set for the vertices in this tutorial.](https://www.delasign.com/CDN/images/Test_2023-11-08-222538_nnib.webp)
Run the code and confirm the shader works as expected.
Looking to learn more about ReactJS and ThreeJS ?
Search our blog to find educational content on learning how to use ReactJS and ThreeJS.