So far, we've focused on animating the position, rotation, and scale of objects. But what about their appearance? Three.js allows us to animate material properties too, such as colors, textures, and even more advanced parameters. This opens up a whole new world of dynamic and visually rich experiences.
The most straightforward way to animate material properties is by directly changing the material's properties over time within our animation loop. For example, to animate the color of a mesh, we can access its material and update its color property.
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); // Start with red
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
function animate() {
requestAnimationFrame(animate);
// Animate color from red to blue
const colorValue = Math.sin(Date.now() * 0.001) * 0.5 + 0.5; // Oscillates between 0 and 1
mesh.material.color.setRGB(colorValue, 0, 1 - colorValue);
renderer.render(scene, camera);
}In the code above, we're using Math.sin to create a smooth oscillation. Date.now() * 0.001 provides a time-based input that changes gradually. By manipulating the RGB values based on this oscillating value, we can create a color-shifting effect. setRGB is a convenient method on Three.js's Color object to set the red, green, and blue components.
Beyond basic colors, you can animate other material properties like transparency (opacity), reflectivity (reflectivity), and emissive color (emissive). The approach remains similar: access the material and modify its properties within the animate function.
// For a material that supports opacity (e.g., MeshLambertMaterial, MeshStandardMaterial)
mesh.material.transparent = true;
mesh.material.opacity = Math.abs(Math.sin(Date.now() * 0.002)); // Animate opacity between 0 and 1When animating opacity, remember to set transparent = true on the material. Otherwise, changes to opacity might not be visible.