Select Page

Animation in Three.js is achieved by modifying the properties of objects in the scene over time. This can be done by updating the properties in a loop, and re-rendering the scene in each iteration of the loop.

Here’s a simple example of how to animate an object’s position in Three.js:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const box = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshBasicMaterial({ color: 0x00ff00 })
);
scene.add(box);

let step = 0;

function animate() {
  requestAnimationFrame(animate);

  // Animate the box's position
  box.position.x = Math.sin(step);
  box.position.y = Math.cos(step);

  step += 0.05;

  renderer.render(scene, camera);
}

animate();

In this example, we create a Mesh object and add it to the scene. In the animate function, we update the position of the box in each iteration of the loop, based on the value of step. This causes the box to move in a sinusoidal pattern, giving the appearance of animation.

You can use similar techniques to animate other properties of objects in the scene, such as rotation, scale, or material properties. By combining multiple animations, you can create more complex and interesting animations in Three.js.