Three.js Animation — Creative Web

Animation = change properties every frame, then render. requestAnimationFrame (or renderer.setAnimationLoop) runs once per screen refresh and stops in a…

Raka's product photo studio has a turntable. It turns at a fixed speed, say one turn every 8 seconds, whether the camera takes 60 or 120 photos a second. That speed belongs to time, not to the number of photos.

Animation in three.js works the same way. You change an object's properties (rotation, position, scale) a little every frame, then render again, and you work out how much from time. In this lesson the Coffee Print Mug from the previous lesson goes on a turntable: it spins by itself, stops smoothly at its print when asked, and hops with a keyframe clip.

The loop: requestAnimationFrame

function animate() {
  requestAnimationFrame(animate); // ask to be called again before the next repaint
  cube.rotation.x += 0.01;
  renderer.render(scene, camera);
}
animate();

Time, not frames: THREE.Timer

rotation.y += 0.01 adds per frame: 0.6 radians a second on a 60 Hz screen, 1.2 on 120 Hz. To make it the same everywhere, multiply a per-second speed by delta, the length of the last frame in seconds.

const timer = new THREE.Timer();
timer.connect(document);  // use the Page Visibility API, covered below
const SPEED = 0.8;        // radians per second: 1 turn = 2π / 0.8 = 7.85 seconds

renderer.setAnimationLoop((time) => {
  timer.update(time);              // once per frame, before reading it
  const delta = timer.getDelta();  // seconds since the previous frame
  turntable.rotation.y += SPEED * delta;
  renderer.render(scene, camera);
});
Screen delta per frame Added per frame Per second
60 Hz 0.0167 s 0.0133 rad 0.8 rad
120 Hz 0.0083 s 0.0067 rad 0.8 rad

Easing: stopping at the print

The "Show the print" button turns the turntable to the nearest multiple of 2π (the print faces the camera, from the Geometry & Material lesson) over 0.8 seconds:

const easeInOutCubic = (p) => (p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2);
function showPrint() {
  spinning = false;
  const to = Math.round(turntable.rotation.y / (2 * Math.PI)) * 2 * Math.PI; // at most half a turn away
  turn = { from: turntable.rotation.y, to, t: 0 };
}
// inside the loop:
if (turn) {
  turn.t += delta;
  const p = Math.min(turn.t / 0.8, 1);   // 0 to 1
  turntable.rotation.y = turn.from + (turn.to - turn.from) * easeInOutCubic(p);
  if (p === 1) turn = null;
}

Easing is a curve that turns progress in time p into progress in motion: at p 0.25 the motion is only at 0.0625, at 0.5 exactly 0.5, at 0.75 already 0.9375. Slow, fast, slow, like someone turning the table by hand. Without easing (p as is), the mug starts and stops dead.

Keyframe clips: AnimationMixer

A keyframe is a value at a given second; three.js fills in the values between. By default it does so in a straight line (linear): halfway in time between two keyframes, the value is halfway too, and a slerped angle also turns at an even rate. The "hop" clip (1.2 seconds) is built by hand, in exactly the shape of a clip that comes from Blender in gltf.animations:

const AXIS_Y = new THREE.Vector3(0, 1, 0);
const q = new THREE.Quaternion();
const hop = new THREE.AnimationClip('hop', 1.2, [
  new THREE.NumberKeyframeTrack('.position[y]', [0, 0.6, 1.2], [0, 0.4, 0]),
  new THREE.QuaternionKeyframeTrack('.quaternion', [0, 0.4, 0.8, 1.2],
    [0, 1, 2, 3].flatMap((i) => q.setFromAxisAngle(AXIS_Y, (i * 2 * Math.PI) / 3).toArray())),
]);
const mixer = new THREE.AnimationMixer(mug);
const action = mixer.clipAction(hop).setLoop(THREE.LoopOnce);
hopButton.addEventListener('click', () => action.reset().play());
// inside the loop, after working out delta:
mixer.update(delta);

Hidden tabs and reduced motion

While the tab is hidden, requestAnimationFrame stops. Say Raka switches to another tab for 10 seconds, then comes back. The first frame arrives 10 seconds after the last one, so if the loop uses timer.getDelta() without connect, the delta is 10 seconds and the turntable, turning 0.8 radians per second, jumps 0.8 × 10 = 8 radians (1.27 turns) in one frame. There are two cures:

For visitors whose system asks for reduced motion (vertigo, motion sickness), don't spin by yourself:

const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
let spinning = !reducedMotion.matches;
reducedMotion.addEventListener('change', () => { spinning = !reducedMotion.matches; });

"Show the print" then moves at once with no animation, and the hop clip is skipped.

Don't make new objects inside the loop

Every new THREE.Vector3() or .clone() in the loop becomes garbage that the garbage collector (GC) cleans up later, and meanwhile JavaScript pauses for a moment. Measured in Chrome (a laptop, 120 fps, 8 seconds, 1,000 steam particles): reusing one vector, 1 GC; new THREE.Vector3() per particle, 7; position.clone() per particle, 34, 6.6 ms in all. On the laptop each pause is only about 0.3 ms; on a phone with a 4 times slower CPU, an estimated 1.3 ms, while a 120 Hz frame is only 8.3 ms. Make temporary objects once, outside the loop:

const temp = new THREE.Vector3();               // once only
for (const p of particles) p.position.add(temp.set(0, 0.3 * delta, 0));

⚠️ A mug that turns too fast, stands still or suddenly jumps

TL;DR: Animation = change properties every frame, then render. requestAnimationFrame (or renderer.setAnimationLoop) runs once per screen refresh and stops in a hidden tab; its callback receives time, not a delta. Work motion out from time: THREE.Timer (update(time), getDelta(), getElapsed()), not THREE.Clock, deprecated since r183; += SPEED * delta, Math.sin(t) * 3 to swing between -3 and 3. Easing (easeInOutCubic) makes starts and stops smooth. Keyframe clips: AnimationClip + NumberKeyframeTrack / QuaternionKeyframeTrack, AnimationMixer, clipAction(...).play(), mixer.update(delta). timer.connect(document) stops the jump after a hidden tab, prefers-reduced-motion turns the auto-spin off, and temporary objects are made once, outside the loop.

⚡ A loop in step with the screen

Write:

function animate() {
  requestAnimationFrame(animate); // ask to be called again before the next repaint
  cube.rotation.x += 0.01;
  renderer.render(scene, camera);
}
animate();
Guess first: the tab is hidden. Which keeps running, setInterval(fn, 16) or requestAnimationFrame?

setInterval, only slowed to at most once a second. requestAnimationFrame stops, so the battery and the GPU rest.

Meaning: requestAnimationFrame is in step with the screen's refresh: once per refresh, 60 times a second on a 60 Hz screen, 120 times on a 120 Hz one.

⚡ Time, not frames

Write:

timer.update(time);              // once per frame, before reading it
const delta = timer.getDelta();  // seconds since the previous frame
turntable.rotation.y += SPEED * delta;

Meaning: += 0.01 per frame is twice as fast on a 120 Hz screen. A per-second speed times delta makes the turntable turn just as fast on any screen.

⚡ Easing and clips

Meaning: Easing like easeInOutCubic makes the motion slow, fast, then slow, so the mug doesn't start and stop dead. A keyframe clip is played by an AnimationMixer, and without mixer.update(delta) every frame, the clip doesn't move at all.

What you will learn