How to Pause and Resume Three.js Animations
This article explains what the AnimationAction class is
in Three.js and provides a clear, step-by-step guide on how to use it to
pause and resume animations. You will learn how to access an animation
action through the AnimationMixer and control its state
using simple JavaScript properties.
What is an AnimationAction?
In Three.js, AnimationAction is a specialized controller
class used to schedule, blend, and control the playback of animations
stored in AnimationClips. You do not instantiate an
AnimationAction directly. Instead, you generate it by
passing an AnimationClip to an AnimationMixer
using the clipAction() method.
Once created, the AnimationAction acts as the interface
for a specific animation clip on a specific 3D object, allowing you to
play, loop, warp, fade, pause, and resume the animation.
How to Pause and Resume the Animation
To pause and resume an animation, you use the paused
property of the AnimationAction object.
When you set the paused property to true,
the animation freeze-frames at its current position. Setting it back to
false resumes the playback from that exact frame, provided
the animation has already been started with the play()
method.
Step-by-Step Code Implementation
Here is how to set up, pause, and resume an animation action:
import * as THREE from 'three';
// 1. Initialize the AnimationMixer for your 3D object
const mixer = new THREE.AnimationMixer(myMesh);
// 2. Retrieve your AnimationClip (usually loaded from a GLTF model)
const clip = gltf.animations[0];
// 3. Create the AnimationAction
const action = mixer.clipAction(clip);
// 4. Start playing the animation
action.play();
// 5. Function to pause the animation
function pauseAnimation() {
action.paused = true;
}
// 6. Function to resume the animation
function resumeAnimation() {
action.paused = false;
}Creating a Toggle Function
In many projects, you will want a single button to toggle between
playing and paused states. You can easily achieve this by checking the
current value of the paused property:
function toggleAnimation() {
// Toggle the paused state
action.paused = !action.paused;
}Updating the Mixer
Remember that for any animation changes to render on screen, you must
update the AnimationMixer inside your main animation render
loop using a clock delta:
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta();
// Updates the animation states, respecting the paused property
mixer.update(delta);
renderer.render(scene, camera);
}
animate();