Change Three.js Material Emissive Color Dynamically
This article explains how to dynamically change the emissive color of a material at runtime in Three.js. You will learn how to access the emissive property of compatible materials, update its color values using different methods, and apply these changes smoothly inside an active animation loop.
1. Choose a Compatible Material
Not all Three.js materials support emissive colors. To use emissive
properties, you must use a material that responds to lighting, such as:
* MeshStandardMaterial * MeshPhongMaterial *
MeshPhysicalMaterial * MeshToonMaterial
Basic materials like MeshBasicMaterial do not support
emissive properties.
// Creating a compatible material
const material = new THREE.MeshStandardMaterial({
color: 0x111111,
emissive: 0x00ff00, // Initial green emissive glow
emissiveIntensity: 1.0
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);2. Access and Modify the Emissive Property
The emissive property of a material is an instance of
THREE.Color. You can modify it at runtime by targeting the
material on your mesh.
There are several ways to update the color:
Method A: Using the
.set() Method (Recommended)
The .set() method is highly versatile as it accepts hex
values, color names, and CSS-style color strings.
// Change using a hexadecimal value
mesh.material.emissive.set(0xff0000); // Red
// Change using a string name
mesh.material.emissive.set('blue');
// Change using an RGB string
mesh.material.emissive.set('rgb(255, 100, 0)');Method B: Using
.setHex()
If you are strictly working with hexadecimal numbers, you can use
.setHex().
mesh.material.emissive.setHex(0x0000ff); // BlueMethod C: Modifying Individual RGB Channels
You can directly manipulate the r, g, and
b properties. In Three.js, these values range from
0.0 to 1.0.
mesh.material.emissive.r = 1.0; // Max Red
mesh.material.emissive.g = 0.5; // Medium Green
mesh.material.emissive.b = 0.0; // No Blue3. Changing the Emissive Intensity
Often, changing the color is not enough; you may also want to control
how brightly the emissive color glows. You can do this by modifying the
emissiveIntensity property.
// Make the glow brighter
mesh.material.emissiveIntensity = 2.5;4. Example: Animating the Color at Runtime
To see the change dynamically, update the color inside your render or animation loop. The following example uses sine waves to smoothly transition the emissive color over time.
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsedTime = clock.getElapsedTime();
// Generate values between 0 and 1 based on time
const r = Math.abs(Math.sin(elapsedTime));
const g = Math.abs(Math.sin(elapsedTime + 2));
const b = Math.abs(Math.sin(elapsedTime + 4));
// Apply the dynamic color to the material
mesh.material.emissive.setRGB(r, g, b);
renderer.render(scene, camera);
}
animate();