Welcome to the heart of bringing your 3D scenes to life: animation! In Three.js, animation is primarily driven by a concept called the 'animation loop'. Think of it as a never-ending cycle that continuously redraws your scene, allowing you to update the position, rotation, scale, or any other property of your 3D objects over time.
At its core, the animation loop is a function that gets called repeatedly by the browser. Inside this function, we do a few key things:
graph TD; A[Start Animation Loop] --> B(Request Next Frame); B --> C{Is Animation Needed?}; C -- Yes --> D(Update Scene Objects); D --> E(Render Scene); E --> B; C -- No --> F[Stop Animation Loop];
The magic happens with requestAnimationFrame(). This is a browser API that tells the browser you want to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. It's far more efficient and smoother than using setInterval() or setTimeout() for animations, as it synchronizes with the browser's rendering cycle.
function animate() {
requestAnimationFrame(animate);
// Update scene objects here
renderer.render(scene, camera);
}The animate() function is our animation loop. The crucial line is requestAnimationFrame(animate);. This tells the browser, 'Hey, when you're ready to draw the next frame, please call this animate function again.' This creates the continuous loop.
Inside the animate function, before we render, we'll add logic to modify our scene's elements. This could involve changing a mesh's position, rotating a light, or animating camera controls. For example, to make a cube spin, we'd update its rotation.y property.
function animate() {
requestAnimationFrame(animate);
cube.rotation.y += 0.01; // Rotate the cube 0.01 radians each frame
renderer.render(scene, camera);
}Finally, renderer.render(scene, camera); redraws the scene with all the updated changes. This cycle repeats hundreds of times per second, creating the illusion of smooth motion.