Three.js is a JavaScript library that is built on top of WebGL and is used to render animations on the web.
There is built-in support for the framework to create and edit colors. This can be done using the objects of the Color class. Colors can be applied to materials in three.js.
There are multiple ways to initialize a Color object in three.js. These are as follows:
Not providing any arguments will initialize the color to white.
const color = new THREE.Color();
// initializes to white
We can also provide the Color constructor with a hexadecimal value of the 0xRRGGBB form. The least significant bytes represent the amount of blue. The most significant bytes represent the amount of red, and the two bytes in the middle represent the amount of green.
const color = new THREE.Color(0xff0000);
// initializes to red
We can also use an RGB string to initialize the Color object. It is of the 'rgb(red, green, blue)' format. Instead of hex, we use decimal numbers to represent the amount of each primary color in the final color. Each primary color can vary between 0 and 255.
const color = new THREE.Color('rgb(0, 255, 0)');
// initializes to green
We can also use the percentages of each primary color instead:
const color = new THREE.Color('rgb(0, 100%, 0)')
// initializes to green
We can also use RGB values between 0 and 1. Letβs suppose that x, y, and z are the concentrations of red, green, and blue we want in our color. Dividing each by 255 will give us the RGB value between 0 and 1:
const color = new THREE.Color(0, 0, 1);
// initializes to blue
X11 color names are strings mapped to pre-defined values of hexadecimal colors:
const color = new THREE.Color("goldenrod");
// initializes to a shade of gold
HSL is an abbreviation for hue, saturation, and lightness. We can use these values as well to define the color we need. HSL strings are of the 'hsl(hue, saturation, lightness)' format. hue ranges from 0β360. saturation and lightness can vary from 0β100%:
const color = new THREE.Color('hsl(255, 100%, 50%)');
The constructor returns an instance of the Color class. The methods and properties applicable to this class can be viewed here.
Here's an example that illustrates the different methods that can be initialized and used in a three.js scene:
The user can interact with the code shown above to change the color of the shape displayed in the scene.
To read more on how to create a scene in three.js, please follow this link.
Lines 38β41: We initialize multiple color variables as explained in the constructor syntax above.
Line 43: We set the color property of material. We can change the color4 variable inside to see the effects of different colors.
Free Resources