AnimationMixer & Clips
Three.js has a full keyframe animation system, the same one that plays the animations inside glTF files. You can also build clips in code for doors, chests, pickups, UI in 3D, and cutscene camera moves. Four classes work together:
| Class | Role |
|---|---|
KeyframeTrack |
keyframe times + values for one property of one object, e.g. "Lid.rotation[x]" |
AnimationClip |
a named set of tracks with a duration: "Open", "Walk", "Idle" |
AnimationMixer |
the player for one object hierarchy (a model); advanced by mixer.update(dt) |
AnimationAction |
one clip playing on one mixer: play/stop, loop mode, speed, weight, fades |
Keyframes and interpolation
A track holds sorted times and the values at those times. Between keyframes the mixer interpolates: linear by default, smooth (THREE.InterpolateSmooth) or stepped (THREE.InterpolateDiscrete). Quaternion tracks use spherical interpolation. This model samples a linear track the way the mixer does:
// Sample a 1D keyframe track at time t (linear interpolation, clamped at the ends).
function sample(times, values, t) {
if (t <= times[0]) return values[0];
if (t >= times[times.length - 1]) return values[values.length - 1];
let i = 1;
while (times[i] < t) i++; // the Three.js interpolants search like this (cached)
const a = (t - times[i - 1]) / (times[i] - times[i - 1]);
return values[i - 1] + (values[i] - values[i - 1]) * a;
}
// A chest lid: closed, opens to -110° in 0.6 s, overshoots slightly, settles.
const times = [0, 0.6, 0.75, 0.9];
const degrees = [0, -115, -105, -110];
for (const t of [0, 0.15, 0.3, 0.6, 0.7, 0.9, 2]) {
console.log(`t=${t.toFixed(2)}s lid ${sample(times, degrees, t).toFixed(1).padStart(7)}°`);
}t=0.00s lid 0.0°
t=0.15s lid -28.8°
t=0.30s lid -57.5°
t=0.60s lid -115.0°
t=0.70s lid -108.3°
t=0.90s lid -110.0°
t=2.00s lid -110.0°
Building clips in code
Track names are property paths: the object's name, a dot, and the property, with an optional component in brackets. The mixer finds the object by name inside its root, so name the objects you animate.
const lidOpen = new THREE.NumberKeyframeTrack('Lid.rotation[x]', [0, 0.6, 0.75, 0.9], [0, -2.0, -1.83, -1.92]);
const bob = new THREE.VectorKeyframeTrack('Coin.position', [0, 1, 2], [0, 1, 0, 0, 1.3, 0, 0, 1, 0]);
const glow = new THREE.ColorKeyframeTrack('Coin.material.emissive', [0, 1, 2], [0, 0, 0, 0.6, 0.4, 0, 0, 0, 0]);
const open = new THREE.AnimationClip('Open', -1, [lidOpen]); // -1: compute the duration from the tracksTrack types: NumberKeyframeTrack (one number), VectorKeyframeTrack (positions, scales), QuaternionKeyframeTrack (rotations; use this rather than three Euler tracks for rotations of more than one axis), ColorKeyframeTrack, BooleanKeyframeTrack and StringKeyframeTrack (stepped).
Playing clips
Click the chest to open or close it. The coin loops forever with two clips at once (a bob and a glow), and the console reports the mixer's finished events.
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block; cursor: pointer }
#hint { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; text-shadow: 0 1px 2px #000; pointer-events: none }</style>
<div id="hint">Click the chest</div>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1e2433');
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 50);
camera.position.set(2.5, 2.6, 5);
camera.lookAt(0.5, 0.6, 0);
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
scene.add(new THREE.HemisphereLight('#fff', '#445', 1.3));
const sun = new THREE.DirectionalLight('#fff', 2.2);
sun.position.set(3, 5, 4);
scene.add(sun);
// A chest: a box base and a lid whose pivot is at the back edge (a Group as the hinge).
const chest = new THREE.Group();
const wood = new THREE.MeshStandardMaterial({ color: '#8d5a32', roughness: 0.8 });
const base = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.7, 0.9), wood);
base.position.y = 0.35;
const lid = new THREE.Group();
lid.name = 'Lid'; // the track targets this name
lid.position.set(0, 0.7, -0.45); // the hinge
const lidMesh = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.25, 0.9), wood);
lidMesh.position.set(0, 0.125, 0.45); // offset so the lid rotates around its back edge
lid.add(lidMesh);
const glowInside = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.05, 0.7), new THREE.MeshBasicMaterial({ color: '#ffd54f' }));
glowInside.position.y = 0.68;
chest.add(base, lid, glowInside);
scene.add(chest);
const coin = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.3, 0.06, 32), new THREE.MeshStandardMaterial({ color: '#ffca28', metalness: 0.3, roughness: 0.4, emissive: '#000000' }));
coin.name = 'Coin';
coin.rotation.x = Math.PI / 2;
coin.position.set(2, 1, 0);
scene.add(coin);
// Clips.
const openClip = new THREE.AnimationClip('Open', -1, [
new THREE.NumberKeyframeTrack('Lid.rotation[x]', [0, 0.6, 0.75, 0.9], [0, -2.0, -1.83, -1.92]),
]);
const bobClip = new THREE.AnimationClip('Bob', -1, [
new THREE.VectorKeyframeTrack('Coin.position', [0, 1, 2], [2, 1, 0, 2, 1.3, 0, 2, 1, 0], THREE.InterpolateSmooth),
new THREE.QuaternionKeyframeTrack('Coin.quaternion', [0, 1, 2], [
...new THREE.Quaternion().setFromEuler(new THREE.Euler(Math.PI / 2, 0, 0, 'YXZ')).toArray(),
...new THREE.Quaternion().setFromEuler(new THREE.Euler(Math.PI / 2, Math.PI, 0, 'YXZ')).toArray(),
...new THREE.Quaternion().setFromEuler(new THREE.Euler(Math.PI / 2, Math.PI * 2, 0, 'YXZ')).toArray(),
]),
]);
const glowClip = new THREE.AnimationClip('Glow', -1, [
new THREE.ColorKeyframeTrack('Coin.material.emissive', [0, 0.5, 1], [0, 0, 0, 0.5, 0.3, 0, 0, 0, 0]),
]);
// One mixer per animated root. The scene works as the root here because both objects are in it.
const mixer = new THREE.AnimationMixer(scene);
mixer.clipAction(bobClip).play(); // LoopRepeat by default
mixer.clipAction(glowClip).play();
const open = mixer.clipAction(openClip);
open.setLoop(THREE.LoopOnce, 1);
open.clampWhenFinished = true; // stay on the last frame instead of resetting
mixer.addEventListener('finished', (e) => console.log(`finished: ${e.action.getClip().name} (timeScale ${e.action.timeScale})`));
let isOpen = false;
const raycaster = new THREE.Raycaster(), pointer = new THREE.Vector2();
renderer.domElement.addEventListener('pointerdown', (e) => {
pointer.set((e.offsetX / innerWidth) * 2 - 1, -(e.offsetY / innerHeight) * 2 + 1);
raycaster.setFromCamera(pointer, camera);
if (!raycaster.intersectObject(chest, true).length) return;
isOpen = !isOpen;
open.paused = false;
open.timeScale = isOpen ? 1 : -1.5; // play backwards (and faster) to close
if (!open.isRunning()) {
open.reset(); // reset() also rewinds time to 0...
if (!isOpen) open.time = openClip.duration; // ...so start closing from the end
open.play();
}
});
const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
timer.update(t);
mixer.update(Math.min(Math.max(timer.getDelta(), 0), 0.1)); // seconds; nothing moves without this
renderer.render(scene, camera);
});
</script>The key settings:
| Action setting | Meaning |
|---|---|
setLoop(THREE.LoopOnce, 1) / LoopRepeat / LoopPingPong |
play once, repeat (default, infinite), or back and forth |
clampWhenFinished |
after a LoopOnce clip ends, hold the last frame (otherwise the action stops and the object snaps back) |
timeScale |
playback speed; negative plays backwards; mixer.timeScale scales everything (slow motion, pause with 0) |
weight, fadeIn(s), fadeOut(s), crossFadeTo(other, s) |
blending between clips (next lesson) |
time, reset(), paused, isRunning() |
direct control of the playhead |
mixer events 'finished', 'loop' |
react when a one-shot ends (e.g. re-enable input after an attack) |
Clips from glTF files
Models from Blender bring their clips along in gltf.animations. Find them by name and play them on a mixer rooted at the model:
const gltf = await loader.loadAsync('models/knight.glb');
const mixer = new THREE.AnimationMixer(gltf.scene);
const clips = gltf.animations;
const idle = mixer.clipAction(THREE.AnimationClip.findByName(clips, 'Idle'));
idle.play();
// every frame: mixer.update(dt);Every animated model instance needs its own mixer (rooted at that instance), but they can all share the same clip objects. A useful trick for crowds: start each instance at a different time (action.time = rng() * clip.duration) so they don't move in lockstep.
Test yourself
What does the track name 'Lid.rotation[x]' refer to?
- A property called
Lidon the clip - The x component of the rotation of the object named
Lidinside the mixer's root - The x position of every object
- A material uniform
A LoopOnce chest-opening clip ends, and the lid snaps shut again. Which setting keeps it open?
action.loop = trueaction.clampWhenFinished = truemixer.timeScale = 0action.weight = 1
Nothing animates even though you called action.play(). What is the most likely cause?
- The clip has no name
mixer.update(dt)is not called every frame- The renderer needs
animate = true - Clips only work with glTF