Animations and Moving the Camera
local graph
Chapter 9 — Animations and Moving the Camera
Section titled “Chapter 9 — Animations and Moving the Camera”In the previous chapters, we saw some simple animations, but nothing too complex. In Chapter 1, Creating Your First 3D Scene with Three.js, we introduced the basic rendering loop, and in the chapters following that, we used that to rotate some simple objects and show a couple of other basic animation concepts.
In this chapter, we’re going to look in more detail at how animation is supported by Three.js. We will look at the following four subjects:
- Basic animations
- Working with the camera
- Morphing and skeleton animation
- Creating animations using external modes
We will start by covering the basic concepts behind animations.
Basic animations
Section titled “Basic animations”Before we look at the examples, let’s do a quick recap of what was shown in Chapter 1, on the render loop. To support animations, we need to tell Three.js to render the scene every so often. For this, we use the standard HTML5 requestAnimationFrame functionality, as follows:
function animate() { requestAnimationFrame(animate); renderer.render(scene, camera);}animate();With this code, we only need to call the render() function once we’ve initialized the scene. In the render() function itself, we use requestAnimationFrame to schedule the next rendering. This way, the browser will make sure the render() function is called at the correct interval (usually around 60 times or 120 times a second). Before requestAnimationFrame was added to browsers, setInterval(function, interval) or setTimeout(function, interval) was used. These would call the specified function once every set interval.
The problem with this approach is that it doesn’t take into account what else is going on. Even if your animation isn’t shown or is in a hidden tab, it is still called and is still using resources. Another issue is that these functions update the screen whenever they are called, and not when it is the best time for the browser, which results in higher CPU usage. With requestAnimationFrame, we don’t tell the browser when it needs to update the screen; we ask the browser to run the supplied function when it’s most opportune. Usually, this results in a frame rate of about 60 or 120 FPS (depending on your hardware). With requestAnimationFrame, your animations will run more smoothly and will be more CPU- and GPU-friendly, and you don’t have to worry about timing issues.
In the next section, we’ll start with creating a simple animation.
Simple animations
Section titled “Simple animations”With this approach, we can very easily animate objects by changing their rotation, scale, position, material, vertices, faces, and anything else you can imagine. In the next render loop, Three.js will render the changed properties. A very simple example, based on the one we already saw in Chapter 7, Points and Sprites, is available in 01-basic-animations.html. The following screenshot shows this example:

Figure 9.1 – Animation after changing its properties
The render loop for this is very simple. First, we initialize the various properties on the userData object, which is a place for custom data stored in the THREE.Mesh itself, and then update these properties on the mesh, using the data we defined on the userData object. In the animation loop, just change the rotation, position, and the scale based on these properties, and Three.js handles the rest. Here’s how we do this:
const geometry = new THREE.TorusKnotGeometry(2, 0.5, 150, 50, 3, 4)const material = new THREE.PointsMaterial({ size: 0.1, vertexColors: false, color: 0xffffff, map: texture, depthWrite: false, opacity: 0.1, transparent: true, blending: THREE.AdditiveBlending})const points = new THREE.Points(geometry, material)points.userData.rotationSpeed = 0points.userData.scalingSpeed = 0points.userData.bouncingSpeed = 0points.userData.currentStep = 0points.userData.scalingStep = 0// in the render loopfunction render() { const rotationSpeed = points.userData.rotationSpeed const scalingSpeed = points.userData.scalingSpeed const bouncingSpeed = points.userData.bouncingSpeed const currentStep = points.userData.currentStep const scalingStep = points.userData.scalingStep points.rotation.x += rotationSpeed points.rotation.y += rotationSpeed points.rotation.z += rotationSpeed points.userData.currentStep = currentStep + bouncingSpeed points.position.x = Math.cos(points.userData.currentStep) points.position.y = Math.abs(Math.sin (points.userData.currentStep)) * 2 points.userData.scalingStep = scalingStep + scalingSpeed var scaleX = Math.abs(Math.sin(scalingStep * 3 + 0.5 * Math.PI)) var scaleY = Math.abs(Math.cos(scalingStep * 2)) var scaleZ = Math.abs(Math.sin(scalingStep * 4 + 0.5 * Math.PI)) points.scale.set(scaleX, scaleY, scaleZ)}There’s nothing spectacular here, but it nicely shows the concept behind the basic animations we will discuss in this book. We just change the scale, rotation, and position properties and Three.js does the rest.
In the next section, we’ll take a quick sidestep. Besides animations, an important aspect that you’ll quickly run into when working with Three.js in more complex scenes is the ability to select objects on the screen using the mouse.
Selecting and moving objects
Section titled “Selecting and moving objects”Even though not directly related to animations, since we’ll be looking at cameras and animations in this chapter, knowing how to select and move objects is a nice addition to the subjects explained in this chapter. Here, we will show you how to do the following:
- Select an object from a scene using the mouse
- Drag an object around the scene with the mouse
We’ll start by looking at the steps you need to take to select an object.
Selecting objects
Section titled “Selecting objects”First, open the selecting-objects.html example, where you’ll see the following:

Figure 9.2 – Randomly placed cubes that can be selected with the mouse
When you move the mouse around the scene, you’ll see that whenever your mouse hits an object, that object is highlighted. You can easily create this by using a THREE.Raycaster. A raycaster will look at your current camera and cast a ray from the camera to your mouse’s position. Based on that, it can calculate which object is hit based on the position of the mouse. To accomplish this, we need to take the following steps:
- Create an object that keeps track of where the mouse is pointing at
- Whenever we move the mouse, update that object
- In the render loop, use this updated information to see which Three.js object we’re pointing at
This is shown in the following code fragment:
// initially set the position to -1, -1let pointer = { x: -1, y: -1}// when the mouse moves update the pointdocument.addEventListener('mousemove', (event) => { pointer.x = (event.clientX / window.innerWidth) * 2 - 1 pointer.y = -(event.clientY / window.innerHeight) * 2 + 1})// an array containing all the cubes in the sceneconst cubes = ...// use in the render loop to determine the object to highlightconst raycaster = new THREE.Raycaster()function render() { raycaster.setFromCamera(pointer, camera) const cubes = scene.getObjectByName('group').children const intersects = raycaster.intersectObjects(cubes) // do something with the intersected objects}Here, we are using THREE.Raycaster to determine which objects intersect the position of the mouse, from the point of the camera. The result (intersects, in the preceding example) contains all the cubes that intersected our mouse because the ray is cast from the camera’s position through to the end of the camera’s range. The first one in this array is the one that we’re hovering over, and the other values in this array (if any) point to objects behind the first mesh. THREE.Raycaster also provides other information about exactly where you hit the object:

Figure 9.3 – Additional information from the raycaster
Here, we clicked on the face object. faceIndex points to the face of the mesh that was selected. The distance value is measured from the camera to the clicked object, and point is the exact position on the mesh where it was clicked. Finally, we have the uv value, which determines, when using textures, where the point that was clicked appears on the 2D texture (ranging from 0 to 1; more information on uv can be found in Chapter 10, Loading and Working With Textures).
Dragging objects
Section titled “Dragging objects”Besides selecting an object, a common requirement is being able to drag and move objects around. Three.js also provides default support for this. If you open the dragging-objects.html example in your browser, you’ll see a similar scene to the one shown in Figure 9*.2*. This time, when you click on an object, you can drag it around the scene:

Figure 9.4 – Dragging an object around the scene using the mouse
To support dragging objects, Three.js uses something called DragControls. This handles everything and provides convenient callbacks whenever the dragging starts and stops. The code to accomplish this is shown here:
const orbit = new OrbitControls(camera, renderer.domElement)orbit.update()const controls = new DragControls(cubes, camera, renderer.domElement)controls.addEventListener('dragstart', function (event) { orbit.enabled = false event.object.material.emissive.set(0x33333)})controls.addEventListener('dragend', function (event) { orbit.enabled = true event.object.material.emissive.set(0x000000)})It is as simple as that. Here, we added DragControls and passed in the elements that can be dragged (in our case, all of the randomly placed cubes). Then, we added two event listeners. The first one, dragstart, is called when we start dragging a cube, whereas dragend is called when we stop dragging an object. In this example, when we start dragging, we disable OrbitControls (which allows us to use the mouse to look around the scene) and change the color of the selected object. Once we stop dragging, we change the color of the object back and enable OrbitControls again.
There is also a somewhat more advanced version of DragControls available called TransformControls. We won’t go into the details of this control, but it allows you to use a simple UI to transform the properties of a mesh. You can find an example of this control when you open transform-controls-html in your browser:

Figure 9.5 – Transform controls allow you to change the properties of a mesh
If you click on the various parts of this control, you can easily change the shape of the cube:

Figure 9.6 – Shape modified using transform controls
For the final example in this chapter, we’ll show you how you can use an alternative way of modifying the properties of an object (as we saw in the first example of this chapter) by using a tweening library.
Animating with Tween.js
Section titled “Animating with Tween.js”Tween.js is a small JavaScript library that you can download from https://github.com/sole/tween.js/ and that you can use to easily define the transition of a property between two values. All the intermediate points between the start and end values are calculated for you. This process is called tweening. For instance, you can use this library to change the x position of a mesh from 10 to 3 in 10 seconds, as follows:
const tween = new TWEEN.Tween({x: 10}).to({x: 3}, 10000).easing(TWEEN.Easing.Elastic.InOut).onUpdate( function () { // update the mesh})Alternatively, you can create a separate object and pass that into the mesh you want to work with:
const tweenData = { x: 10}new TWEEN.Tween(tweenData) .to({ x: 3 }, 10000) .yoyo(true) .repeat(Infinity) .easing(TWEEN.Easing.Bounce.InOut) .start()mesh.userData.tweenData = tweenDataIn this example, we’ve created TWEEN.Tween. This tween will make sure that the x property is changed from 10 to 3 over 10,000 milliseconds. Tween.js also allows you to define how this property is changed over time. This can be done using linear, quadratic, or any of the other possibilities (see http://sole.github.io/tween.js/examples/03_graphs.html for a complete overview). The value is changed over time by a process called easing. With Tween.js, you configure this using the easing() function. This library also provides additional ways to control how this easing is done. For instance, we can set how often the easing should be repeated (repeat(10)) and whether we want a yoyo effect (this means we go from 10 to 3 and back to 10 in this example).
Using this library together with Three.js is very simple. If you open the tween-animations.html example, you will see the Tween.js library in action. The following screenshot shows a still image of the example:

Figure 9.7 – Tweening a point system halfway through the action
We’ll use the Tween.js library to move this to a single point using a specific easing(), which at a certain point looks as follows:

Figure 9.8 – Tweening a point when everything is merged into a single point
In this example, we’ve taken a point cloud from Chapter 7, and created an animation where all the points slowly move down to the center. The position of these particles is set by using a tween created with the Tween.js library, as follows:
const geometry = new THREE.TorusKnotGeometry(2, 0.5, 150, 50, 3, 4)geometry.setAttribute('originalPos', geometry.attributes['position'].clone())const material = new THREE.PointsMaterial(..)const points = new THREE.Points(geometry, material)const tweenData = { pos: 1}new TWEEN.Tween(tweenData) .to({ pos: 3 }, 10000) .yoyo(true) .repeat(Infinity) .easing(TWEEN.Easing.Bounce.InOut) .start()points.userData.tweenData = tweenData// in the render loopconst originalPosArray = points.geometry.attributes.originalPos.arrayconst positionArray = points.geometry.attributes.position.arrayTWEEN.update() for (let i = 0; i < points.geometry.attributes.position.count; i++) { positionArray[i * 3] = originalPosArray[i * 3] * points.userData.tweenData.pos positionArray[i * 3 + 1] = originalPosArray[i * 3 + 1] * points.userData.tweenData.pos positionArray[i * 3 + 2] = originalPosArray[i * 3 + 2] * points.userData.tweenData.pos}points.geometry.attributes.position.needsUpdate = trueWith this piece of code, we created a tween that transitions a value from 1 to 0 and back again. To use the value from the tween, we have two different options: we can use the onUpdate function provided by this library to call a function with the updated values, whenever the tween is updated (which is done by calling TWEEN.update()), or we can directly access the updated values. In this example, we used the latter approach.
Before we look at the changes we need to make in the render function, we must perform one additional step after we load the model. We want to tween between the original values to zero and back again. For this, we need to store the original positions of the vertices somewhere. We can do this by copying the starting positions array:
geometry.setAttribute('originalPos', geometry.attributes['position'].clone())Now, whenever we want to access the original position, we can look at the originalPos attribute on the geometry. Now, we can just use the value from the tween to calculate the new positions of each of the vertices. We can do this like so in the render loop:
const originalPosArray = points.geometry.attributes.originalPos.arrayconst positionArray = points.geometry.attributes.position.arrayfor (let i = 0; i < points.geometry.attributes.position.count; i++) { positionArray[i * 3] = originalPosArray[i * 3] * points.userData.tweenData.pos positionArray[i * 3 + 1] = originalPosArray[i * 3 + 1] * points.userData.tweenData.pos positionArray[i * 3 + 2] = originalPosArray[i * 3 + 2] * points.userData.tweenData.pos}points.geometry.attributes.position.needsUpdate = trueWith these steps in place, the tween library will take care of positioning the various points on the screen. As you can see, using this library is much easier than having to manage the transitions yourself. Besides animating and changing objects, we can also animate a scene by moving the camera around. In the previous chapters, we did this a couple of times by manually updating the position of the camera. Three.js also provides several additional ways of updating the camera.
Working with the camera
Section titled “Working with the camera”Three.js has several camera controls you can use to control the camera throughout a scene. These controls are located in the Three.js distribution and can be found in the examples/js/controls directory. In this section, we’ll look at the following controls in more detail:
ArcballControls: An extensive control that provides a transparent overlay that you can use to easily move the camera around.FirstPersonControls: These are controls that behave like those in first-person shooters. You can move around with the keyboard and look around with the mouse.FlyControls: These are flight simulator-like controls. You can move and steer with the keyboard and the mouse.OrbitControls: This simulates a satellite in orbit around a specific scene. This allows you to move around with the mouse and keyboard.PointerLockControls: These are similar to the first-person controls but they also lock the mouse pointer to the screen, making it a great choice for simple games.TrackBallControls: These are the most-used controls, allowing you to use the mouse (or the trackball) to easily move, pan, and zoom around the scene.
Besides using these camera controls, you can also move the camera yourself by setting its position and changing where it is pointed using the lookAt() function.
The first control we’ll look at is ArcballControls.
ArcballControls
Section titled “ArcballControls”The easiest way to explain how ArcballControls works is by looking at an example. If you open up the arcball-controls.html example, you’ll see a simple scene, like this:

Figure 9.9 – Using ArcballControls to explore a scene
If you look closely at this screenshot, you will see two translucent lines crossing the scene. These are lines provided by ArcballControls, which you can use to rotate and pan around the scene. These lines are called gizmos. The left mouse button is used to rotate the scene, the right mouse button can be used to pan around, and you can zoom in with the scroll wheel.
Besides this standard functionally, this control also allows you to focus on specific parts of the mesh that is shown. If you double-click on the scene, the camera will focus on that part of the scene. To use this control, all we need to do is instantiate it and pass in the camera property, the domElement property used by the renderer, and the scene property we’re looking at:
import { ArcballControls } from 'three/examples/jsm/controls/ArcballControls'const controls = new ArcballControls(camera, renderer.domElement, scene)controls.update()This control is a very versatile one, which can be configured through a set of properties. Most of these properties can be explored in this example by using the menu on the right of this example. For this specific control, we’ll dive a bit deeper into the properties and methods provided by this object since it is a versatile control and a good choice when you want to provide a good way for your users to explore your scenes. Let’s provide an overview of the properties and the methods provided by this control. First, let’s look at the properties:
adjustNearFar: If this is set totrue, this control will change the camera’snearandfarproperties when zooming incamera: The camera that’s used when creating this controlcursorZoom: If set totrue, when zooming in, the zoom will be focused on the position of the cursordampingFactor: IfenableAnimationsis set totrue, this value will determine how quickly an animation stops after an actiondomElement: This element is used to list mouse eventsenabled: Determines whether this control is enabled or notenableRotate,enableZoom,enablePan,enableGrid,enableAnimations: These properties enable and disable functionality provided by this controlfocusAnimationTime: When we double-click and focus on part of the scene, this property determines the duration of the focusing animationmaxDistance/minDistance: How far we can zoom out and in forPerspectiveCameramaxZoom/minZoom: How far we can zoom out and in forOrthographicCamerascaleFactor: How fast we zoom in and outscene: The scene passed in the constructorradiusFactor: The size of the “gizmo” relative to the screen’s width and heightwMax: How fast we’re allowed to rotate the scene
This control also provides several methods to interact or configure it further:
activateGizmos(bool): Iftrue, it highlights the gizmoscopyState(),pasteState(): Allows you to copy and paste the state of the controls to the clipboard in JSONsaveState(),reset(): Internally saves the current state and usesreset()to apply the saved statedispose(): Removes all parts of this control from the scene, and cleans up any listeners and animationssetGizomsVisible(bool): Specifies whether to show or hide the gizmossetTbRadius(radiusFactor): Updates theradiusFactorproperty and redraws the gizmossetMouseAction(operation, mouse, key): Determines which mouse key provides which actionunsetMouseAction(mouse, key): Clears an assigned mouse actionupdate(): Whenever the camera properties change, call this to apply these new settings to this controlgetRayCaster(): Provides access torayCaster, which is used internally by these controls
ArcballControls is a really useful and relatively new addition to Three.js that provides advanced control of the scene using the mouse. If you’re looking for a simpler approach, you can use TrackBallControls.
TrackBallControls
Section titled “TrackBallControls”Using TrackBallControls follows the same approach as we saw for ArcballControls:
import { TrackBallControls } from 'three/examples/jsm/ controls/TrackBallControls'const controls = new TrackBallControls(camera, renderer. domElement)This time, we just need to pass in the camera and domeElement properties from the renderer. For the trackball controls to work, we also need to add a THREE.Clock and update the render loop, like so:
const clock = new THREE.Clock()function animate() { requestAnimationFrame(animate) renderer.render(scene, camera) controls.update(clock.getDelta())}In the preceding code snippet, we can see a new Three.js object, THREE.Clock. The THREE.Clock object can be used to calculate the elapsed time that a specific invocation or rendering loop takes to complete. You can do this by calling the clock.getDelta() function. This function will return the elapsed time between this call and the previous call to getDelta(). To update the position of the camera, we can call the TrackBallControls.update() function. In this function, we need to provide the time that has passed since the last time this update function was called. For this, we can use the getDelta() function from the THREE.Clock object. You might be wondering why we don’t just pass in the frame rate (1/60 seconds) to the update function. The reason is that with requestAnimationFrame, we can expect 60 FPS, but this isn’t guaranteed. Depending on all kinds of external factors, the frame rate might change. To make sure the camera turns and rotates smoothly, we need to pass in the exact elapsed time.
A working example of this can be found in trackball-controls-camera.html. The following screenshot shows a still image of this example:

Figure 9.10 – Using TrackBallControls to control a scene
You can control the camera in the following manner:
- Left mouse button and move: Rotate and roll the camera around the scene
- Scroll wheel: Zoom in and zoom out
- Middle mouse button and move: Zoom in and zoom out
- Right mouse button and move: Pan around the scene
There are a couple of properties that you can use to fine-tune how the camera acts. For instance, you can set how fast the camera rotates with the rotateSpeed property and disable zooming by setting the noZoom property to true. In this chapter, we won’t go into detail on what each property does as they are pretty much self-explanatory. For a complete overview of what is possible, look at the source of the TrackBallControls.js file, where these properties are listed.
FlyControls
Section titled “FlyControls”The next control we’ll look at is FlyControls. With FlyControls, you can fly around a scene using controls also found in flight simulators. An example can be found in fly-controls-camera.html. The following screenshot shows a still image of this example:

Figure 9.11 – Using FlyControls to fly around a scene
Enabling FlyControls works in the same manner as the other controls:
import { FlyControls } from 'three/examples/jsm/controls/FlyControls'const controls = new FlyControls(camera, renderer.domElement)const clock = new THREE.Clock()function animate() { requestAnimationFrame(animate) renderer.render(scene, camera) controls.update(clock.getDelta())}FlyControls takes the camera and the renderer’s domElement as arguments and requires that you call the update() function with the elapsed time in the render loop. You can control the camera with THREE.FlyControls in the following manner:
- Left and middle mouse buttons: Start moving forward
- Right mouse button: Move backward
- Mouse movement: Look around
- W: Start moving forward
- S: Move backward
- A: Move left
- D: Move right
- R: Move up
- F: Move down
- Left, right, up, and down arrows: Look left, right, up, and down, respectively
- G: Roll left
- E: Roll right
The next control we’ll look at is THREE.FirstPersonControls.
FirstPersonControls
Section titled “FirstPersonControls”As the name implies, FirstPersonControls allows you to control the camera just like in a first-person shooter. The mouse is used to look around, and the keyboard is used to walk around. You can find an example in 07-first-person-camera.html. The following screenshot shows a still image of this example:

Figure 9.12 – Exploring a scene using the first-person controls
Creating these controls follows the same principles as the ones followed for the other controls we’ve seen so far:
Import { FirstPersonControls } from 'three/examples/jsm/ controls/FirstPersonControls'const controls = new FirstPersonControls(camera, renderer.domElement)const clock = new THREE.Clock()function animate() { requestAnimationFrame(animate) renderer.render(scene, camera) controls.update(clock.getDelta())}The functionality provided by this control is pretty straightforward:
- Mouse movement: Look around
- Left, right, up, and down arrows: Move left, right, forward, and backward, respectively
- W: Move forward
- A: Move left
- S: Move backward
- D: Move right
- R: Move up
- F: Move down
- Q: Stop all movement
For the final control, we’ll move on from this first-person perspective to the perspective from space.
OrbitControls
Section titled “OrbitControls”The OrbitControls control is a great way to rotate and pan around an object in the center of the scene. This is also the control we used in the other chapters to provide you with a simple way to explore the models in the examples provided.
With orbit-controls-orbit-camera.html, we’ve included an example that shows how this control works. The following screenshot shows a still image of this example:

Figure 9.13 – OrbitControls properties
Using OrbitControls is just as simple as using the other controls. Include the correct JavaScript file, set up the control with the camera, and use THREE.Clock again to update the control:
import { OrbitControls } from 'three/examples/jsm/ controls/OrbitControls'const controls = new OrbitControls(camera, renderer. domElement)const clock = new THREE.Clock()function animate() { requestAnimationFrame(animate) renderer.render(scene, camera) controls.update(clock.getDelta())}The controls for OrbitControls are focused on using the mouse, as shown in the following list:
- Left mouse click and move: Rotate the camera around the center of the scene
- Scroll wheel or middle mouse click and move: Zoom in and zoom out
- Right mouse click and move: Pan around the scene
That’s it for the camera and moving it around. In this section, we saw a lot of controls that allow you to easily interact with and move through a scene by changing the camera properties. In the next section, we’ll look at more advanced methods of animation: morphing and skinning.
Morphing and skeleton animation
Section titled “Morphing and skeleton animation”When you create animations in external programs (for instance, Blender), you usually have two main options to define animations:
- Morph targets: With morph targets, you define a deformed version – that is, a key position – of the mesh. For this deformed target, all vertex positions are stored. All you need to do to animate the shape is move all the vertices from one position to another key position and repeat that process. The following screenshot shows various morph targets used to show facial expressions (this screenshot has been provided by the Blender foundation):

Figure 9.14 – Setting up animations using morph targets
- Skeleton animation: An alternative is using skeleton animation. With skeletal animation, you define the skeleton – that is, the bones – of the mesh and attach vertices to the specific bones. Now, when you move a bone, any connected bone is also moved appropriately, and the attached vertices are moved and deformed based on the position, movement, and scaling of the bone. The following screenshot, once again provided by the Blender foundation, shows an example of how bones can be used to move and deform an object:

Figure 9.15 – Setting up animations using bones
Three.js supports both modes, but there can be an issue getting a good export when you want to work with skeleton/bones-based animations. For the best results, you should export or convert your model into glTF format, which is becoming the default for exchanging models, animations, and scenes, and has great support from Three.js.
In this section, we’ll look at both options and also look at a couple of external formats supported by Three.js in which animations can be defined.
Animation with morph targets
Section titled “Animation with morph targets”Morph targets are the most straightforward way of defining an animation. You define all the vertices for each important position (also called keyframes) and tell Three.js to move the vertices from one position to the other.
We’ll show you how to work with morph targets using two examples. In the first example, we’ll let Three.js handle the transition between the various keyframes (or morph targets, as we’ll call them from now on), and in the second one, we’ll do this manually. Keep in mind that we are only scratching the surface of what is possible with animations in Three.js. As you’ll see in this section, Three.js has excellent support for controlling animations, supports syncing of animations, and provides ways to smoothly transition from one animation to another, warranting a book just on this subject. So, in the next couple of sections, we’ll provide you with the basics of animations in Three.js, which should provide you with enough information to get started and explore the more complex subjects.
Animation with a mixer and morph targets
Section titled “Animation with a mixer and morph targets”Before we dive into the examples, first, we’ll look at the three core classes that you can use to animate with Three.js. Later in this chapter, we’ll show you all the functions and properties provided by these objects:
THREE.AnimationClip: When you load a model that contains animations, you can look in theresponseobject for a field usually calledanimations. This field will contain a list ofTHREE.AnimationClipobjects. Note that depending on the loader, an animation might be defined on aMesh, aScene, or be provided completely separately. ATHREE.AnimationClipmost often holds the data for a certain animation the model you loaded can perform. For instance, if you loaded a model of a bird, oneTHREE.AnimationClipwould contain the information needed to flap the wings, and another one might be opening and closing its beak.THREE.AnimationMixer:THREE.AnimationMixeris used to control severalTHREE.AnimationClipobjects. It makes sure the timing of the animation is correct and makes it possible to sync animations together, or cleanly move from one animation to another.THREE.AnimationAction:THREE.AnimationMixeritself doesn’t expose a large number of functions to control the animation, though. This is done throughTHREE.AnimationActionobjects, which are returned when you add aTHREE.AnimationClipto aTHREE.AnimationMixer(though you can get them at a later time by using functions provided byTHREE.AnimationMixer).
There is also an AnimationObjectGroup, which you can use to provide the animation state not just to a single Mesh but to a group of objects.
In the following example, you can control a THREE.AnimationMixer and a THREE.AnimationAction, which were created using a THREE.AnimationClip from the model. The THREE.AnimationClip objects used in this example morph a model into a cube and then into a cylinder.
For this first morphing example, the easiest way to understand how a morph targets-based animation works is by opening up the morph-targets.html example. The following screenshot shows a still image of this example:

Figure 9.16 – Animation using morph targets
In this example, we’ve got a simple model (a monkey’s head), which can be transformed into either a cube or a cylinder using morph targets. You can easily test this yourself by moving the cubeTarget or coneTarget sliders, and you’ll see the head being morphed into a different shape. For instance, with cubeTarget at 0.5, you will see that we’re halfway through morphing the monkey’s initial head into a cube. Once it is at 1, the initial geometry is morphed completely:

Figure 9.17 – Same model, but now with cubeTarget set to 1
And that’s the basics of how morph animations work. You’ve got several morphTargets (influences) you can control, and based on their value (from 0 to 1), the vertices move into the desired position. An animation that uses morph targets uses this approach. It just defines at which time certain vertex positions should occur. When running the animation, Three.js will make sure the right values are passed to the morphTargets property of the Mesh instance.
To run the predefined animation, you can open the AnimationMixer menu for this example, and click Play. You’ll see that the head will first transform into a cube and then into a cylinder, before moving back into the shape of a head.
Setting up the required components to accomplish this in Three.js can be done using the following pieces of code. First, we have to load the model. In this example, we exported this example from Blender into glTF, so our animations are at the top level. We simply add these to a variable that we can access in the other parts of the code. We could also set this as a property on the mesh or add it to the userdata property of Mesh:
let animations = []const loadModel = () => { const loader = new GLTFLoader() return loader.loadAsync('/assets/models/blender-morph-targets/morph-targets.gltf').then((container) => { animations = container.animations return container.scene })}Now that we’ve got an animation from the loaded model, we can set up the specific Three.js components so that we can play them:
const mixer = new THREE.AnimationMixer(mesh)const action = mixer.clipAction(animations[0])action.play()There is one final step we need to take so that the correct shape of the mesh is shown whenever we render something, and that is adding a single line to the render loop:
// in render loopmixer.update(clock.getDelta())Here, we used THREE.Clock again to determine the time that’s passed between now and the previous render loop, and called mixer.update(). This information is used by the mixer to determine how far it should morph the vertices to the next morph target (keyframe).
THREE.AnimationMixer and THREE.AnimationClip provide several other functions that you can use to control the animation or create new THREE.AnimationClip objects. You can experiment with them by using the menu on the right in the examples for this section. We will start with THREE.AnimationClip:
duration: The duration of this track (in seconds).name: The name of this clip.tracks: The internal property used to keep track of how certain properties of the model are animated.uuid: The unique ID of this clip. This is assigned automatically.clone(): Makes a copy of this clip.optimize(): This optimizesTHREE.AnimationClip.resetDuration(): This determines the correct duration of this clip.toJson(): Converts this clip into a JSON object.trim(): This trims all the internal tracks to the duration set on this clip.validate(): Does some minimal validation to see if this is a valid clip.CreateClipsFromMorphTargetSequences( name, morphTargetSequences,fps, noLoop): This creates a list ofTHREE.AnimationClipinstances based on a set of morph target sequences.CreateFromMorpTargetSequences( name, morphTargetSequence,fps,noLoop): This creates a singleTHREE.AnimationClipfrom a sequence of morph targets.findByName(objectOrClipArray, name): Searches for aTHREE.AnimationClipby name.parseandtoJson: Allow you to restore and save aThree.AnimationClipas JSON, respectively.parseAnimation(animation, bones): Converts anTHREE.AnimationClipinto JSON.
Once you’ve got a THREE.AnimationClip, you can pass it into the THREE.AnimationMixer object, which provides the following functionality:
AnimationMixer(rootObject): The constructor for this object. This constructor takes aTHREE.Object3Das an argument (for example, aTHREE.Meshof aTHREE.Group).time: The global time for this mixer. This starts at 0, at the time when this mixer is created.timeScale: This can be used to speed up or slow down all the animations managed by this mixer. If the value of this property is set to 0, all the animations are effectively paused.clipAction(animationClip, optionalRoot): This creates aTHREE.AnimationActionthat can be used to control the passed-inTHREE.AnimationClip. If the animation clip is for a different object than what was provided in the constructor ofAnimationMixer, you can pass that in as well.existingAction(animationClip, optionalRoot): This returns theTHREE.AnimationActionproperty, which can be used to control the passed-inTHREE.AnimationClip. Once again, ifTHREE.AnimationClipis for a differentrootObject, you can also pass that in.
When you get THREE.AnimationClip back, you can use it to control the animation:
clampWhenFinished: When set totrue, this will cause the animation to be paused when it reaches its last frame. The default isfalse.enabled: When set tofalse, this will disable the current action so that it does not affect the model. When the action is re-enabled, the animation will continue where it left off.loop: This is the looping mode of this action (which can be set using thesetLoopfunction). This can be set to the following:THREE.LoopOnce: Plays the clip only one timeTHREE.LoopRepeat: Repeats the clip based on the number of repetitions that have been setTHREE.LoopPingPong: Plays the clip based on the number of repetitions, but alternates between playing the clip forward and backward
paused: Setting this property totruewill pause the execution of this clip.repetitions: The number of times the animation will be repeated. This is used by theloopproperty. The default isInfinity.time: The time this action has been running. This is wrapped from 0 to the duration of the clip.timeScale: This can be used to speed up or slow down this animation. If the value of this property is set to0, this animation is effectively paused.weight: This specifies the effect this animation has on the model from a scale of0to1. When set to0, you won’t see any transformation of the model from this animation, and when set to1, you will see the full effect of this animation.zeroSlopeAtEnd: When set to true (which is the default), this will make sure there is a smooth transition between separate clips.zeroSlopeAtStart: When set to true (which is the default), this will make sure there is a smooth transition between separate clips.crossFadeFrom(fadeOutAction, durationInSeconds, warpBoolean): This causes this action to fade in, whilefadeOutActionis faded out. The total fade takesdurationInSeconds. This allows for smooth transitions between animations. WhenwarpBooleanis set totrue, it will apply additional smoothing of timescales.crossFadeTo(fadeInAction, durationInSeconds, warpBoolean): Same ascrossFadeFrom, but this time, it fades in the provided action, and fades out this action.fadeIn(durationInSeconds): Increases theweightproperty slowly from0to1within the passed time interval.fadeOut(durationInSeconds): Decreases theweightproperty slowly from0to1within the passed time interval.getEffectiveTimeScale(): Returns the effective timescale based on the currently running warp.getEffectiveWeight(): Returns the effective weight based on the currently running fade.getClip(): Returns theTHREE.AnimationClipproperty this action is managing.getMixer(): Returns the mixer that is playing this action.getRoot(): Gets the root object that is controlled by this action.halt(durationInSeconds): Gradually decreasestimeScaleto0withindurationInSeconds.isRunning(): Checks whether the animation is currently running.isScheduled(): Checks whether this action is currently active in the mixer.play(): Starts running this action (starting the animation).reset(): Resets this action. This will result in settingpausedtofalse,enabledtotrue, andtimeto0.setDuration(durationInSeconds): Sets the duration of a single loop. This will changetimeScaleso that the complete animation can play withindurationInSeconds.setEffectiveTimeScale(timeScale): SetstimeScaleto the provided value.setEffectiveWeight(): Setsweightto the provided value.setLoop(loopMode, repetitions): SetsloopModeand the number ofrepetitions. See theloopproperty for the options and their effect.startAt(startTimeInSeconds): Delays starting the animation forstartTimeInSeconds.stop(): Stops this action, andresetis applied.stopFading(): Stops any scheduled fading.stopWarping(): Stops any schedule warping.syncWith(otherAction): Syncs this action with the passed-in action. This will set this action’stimeandtimeScalevalue to the passed-in action.warp(startTimeScale, endTimeScale, durationInSeconds): Changes thetimeScaleproperty fromstartTimeScaletoendTimeScalewithin the specifieddurationInSeconds.
Besides all the functions and properties that you can use to control the animation, THREE.AnimationMixer also provides two events you can listen to by calling addEventListener on the mixer. The "loop" event is sent when a single loop is finished, and the "finished" event is sent when the complete action has finished.
Animation using bones and skinning
Section titled “Animation using bones and skinning”As we saw in the Animation with a mixer and morph targets section, morph animations are very straightforward. Three.js knows all the target vertex positions and only needs to transition each vertex from one position to the next. For bones and skinning, it becomes a bit more complex. When you use bones for animation, you move the bone, and Three.js has to determine how to translate the attached skin (a set of vertices) accordingly. For this example, we will use a model that was exported from Blender into Three.js format (lpp-rigging.gltf in the models/blender-skeleton folder). This is a model of a person, complete with a set of bones. By moving the bones around, we can animate the complete model. First, let’s look at how we loaded the model:
let animations = []const loadModel = () => { const loader = new GLTFLoader() return loader.loadAsync('/assets/models/blender- skeleton/lpp-rigging.gltf').then((container) => { container.scene.translateY(-2) applyShadowsAndDepthWrite(container.scene) animations = container.animations return container.scene })}We’ve exported the model in glTF format since the support for glTF in Three.js is good. Loading a model for bone animation isn’t that different than any of the other models. We just specify the model file and load it like any other glTF file. For glTF, the animations are in a separate property of the object that is loaded, so we simply assign it to the animations variable for easy access.
In this example, we’ve added a console log, which shows what THREE.Mesh looks like once we’ve loaded it:

Figure 9.18 – The skeleton structure is reflected in the hierarchy of objects
Here, you can see that the mesh consists of a tree of bones and meshes. This also means that if you move a bone, the relevant meshes will be moved alongside it.
The following screenshot shows a still image of this example:

Figure 9.19 – Manually changing the rotation of the arm and leg bones
This scene also contains an animation, which you can trigger by checking the animationIsPlaying checkbox. This will override the manually set bones’ positions and rotations, and has the skeleton kind of jumping up and down:

Figure 9.20 – Playing a skeleton animation
To set up this animation, we must follow the same steps we saw earlier:
const mixer = new THREE.AnimationMixer(mesh)const action = mixer.clipAction(animations[0])action.play()As you can see, working with bones is just as easy as working with fixed morph targets. In this example, we’ve only adjusted the rotation of the bones; you can also move the position or change the scale. In the next section, we will look at loading animations from external models.
Creating animations using external models
Section titled “Creating animations using external models”In Chapter 8, Creating and Loading Advanced Meshes and Geometries, we looked at several 3D formats that are supported by Three.js. A couple of those formats also support animations. In this chapter, we’ll look at the following examples:
- COLLADA model: The COLLADA format has support for animations. For this example, we’ll load an animation from a COLLADA file and render it with Three.js.
- MD2 model: The MD2 model is a simple format used in the older Quake engines. Even though the format is a bit dated, it is still a very good format for storing character animations.
- glTF models: GL transmission format (glTF) is a format specifically designed for storing 3D scenes and models. It focuses on minimizing the size of the assets and tries to be as efficient as possible in unpacking the models.
- FBX model: FBX is a format produced by the Mixamo tooling available at https://www.mixamo.com. With Mixamo, you can easily rig and animate models, without needing lots of modeling experience.
- BVH model: The Biovision (BVH) format is a slightly different one compared to the other loaders. With this loader, you don’t load a geometry with a skeleton or a set of animations. With this format, which is used by Autodesk MotionBuilder, you just load a skeleton, which you can visualize or even attach to your geometry.
We’ll start with a glTF model since this format is becoming the standard for exchanging models between different tools and libraries.
Using gltfLoader
Section titled “Using gltfLoader”A format that is getting more and more attention lately is the glTF format. This format, for which you can find a very extensive explanation at https://github.com/KhronosGroup/glTF, focuses on optimizing size and resource usage. Using glTFLoader is similar to using the other loaders:
import { GLTFLoader } from 'three/examples /jsm/loaders/GLTFLoader'...return loader.loadAsync('/assets/models/truffle_man/scene.gltf'). then((container) => { container.scene.scale.setScalar(4) container.scene.translateY(-2) scene.add(container.scene)
const mixer = new THREE.AnimationMixer( container.scene ); const animationClip = container.animations[0]; const clipAction = mixer.clipAction( animationClip ).play();})This loader also loads a complete scene, so you can either add everything to the group or select child elements. For this example, you can view the results by opening load-gltf.js:

Figure 9.21 – Animation loaded using glTF
For the next example, we’ll use the FBX model.
Visualizing motions captured models using fbxLoader
Section titled “Visualizing motions captured models using fbxLoader”The Autodesk FBX format has been around for a while and is very easy to use. There is a great resource online where you can find many animations that you can download in this format: https://www.mixamo.com/. This site provides 2,500 animations that you can use and customize:

Figure 9.22 – Loading animations from mixamo
After downloading an animation, using it from Three.js is easy:
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader'...loader.loadAsync('/assets/models/salsa/salsa.fbx').then((mesh) => { mesh.translateX(-0.8) mesh.translateY(-1.9) mesh.scale.set(0.03, 0.03, 0.03) scene.add(mesh) const mixer = new THREE.AnimationMixer(mesh) const clips = mesh.animations const clip = THREE.AnimationClip.findByName(clips, 'mixamo.com')})The resulting animation, as you can see in load-fbx.html, looks great:

Figure 9.23 – Animation loaded using fbx
FBX and glTF are modern formats that are used a lot and are a good way to exchange models and animations. There are a couple of older formats around as well. An interesting one is a format used by the old FPS Quake: MD2.
Loading an animation from a Quake model
Section titled “Loading an animation from a Quake model”The MD2 format was created to model characters from Quake, a great game from 1996. Even though the newer engines use a different format, you can still find a lot of interesting models in the MD2 format. Using an MD2 file is a bit different than using the others we’ve seen so far. When you load an MD2 model, you get a geometry, so you have to make sure that you create a material as well and assign a skin:
let animations = []const loader = new MD2Loader()loader.loadAsync('/assets/models/ogre/ogro.md2').then ((object) => { const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, metalness: 0, map: new THREE.TextureLoader().load ('/assets/models/ogre/skins/skin.jpg') }) animations = object.animations const mesh = new THREE.Mesh(object, mat) // add to scene, and you can animate it as we've seen already})Once you have this Mesh, setting up the animation works in the same way. The result of this animation can be seen here (load-md2.html):

Figure 9.24 – Loaded Quake monster
Next up is COLLADA.
Loading an animation from a COLLADA model
Section titled “Loading an animation from a COLLADA model”While the normal COLLADA models aren’t compressed (and they can get quite large), there is also a KMZLoader available in Three.js. This is a compressed COLLADA model, so if you run into Keyhole Markup Language Zipped (KMZ) models, you can load the model using KMZLoader instead of ColladaLoader:

Figure 9.25 – Loaded COLLADA model
For the final loader, we’ll look at BVHLoader.
Visualizing a skeleton with BVHLoader
Section titled “Visualizing a skeleton with BVHLoader”BVHLoader is a slightly different loader than the ones we’ve seen so far. This loader doesn’t return meshes or geometries with animations; instead, it returns a skeleton and an animation. An example of this is shown in load-bvh.html:

Figure 9.26 – Loaded BVH skeleton
To visualize this, we can use a THREE.SkeletonHelper, as seen here. With a THREE.SkeletonHelper, we can visualize the skeleton of a mesh. BVH models just contain skeleton information, which we can visualize like this:
const loader = new BVHLoader()let animation = undefinedloader.loadAsync('/assets/models//amelia-dance/DanceNightClub7_t1.bvh').then((result) => { const skeletonHelper = new THREE.SkeletonHelper (result.skeleton.bones[0]) skeletonHelper.skeleton = result.skeleton const boneContainer = new THREE.Group() boneContainer.add(result.skeleton.bones[0]) animation = result.clip const group = new THREE.Group() group.add(skeletonHelper) group.add(boneContainer) group.scale.setScalar(0.2) group.translateY(-1.6) group.translateX(-3) // Now we can animate the group just like we did for the other examples})In older versions of Three.js, there was support for other kinds of animation file formats. Most of those are obsolete and have subsequently been removed from the Three.js distribution. If you do stumble upon a different format in which you want to show the animations, you can look at the older Three.js releases and possibly reuse the loaders from there.
Summary
Section titled “Summary”In this chapter, we looked at different ways you can animate your scene. We started with some basic animation tricks, moved on to camera movement and control, and ended by looking at animating models using morph targets and skeleton/bones animations.
When you have the render loop in place, adding simple animations is very easy. Just change a property of the mesh; in the next rendering step, Three.js will render the updated mesh. For more complex animations, you would usually model them in external programs and load them through one of the loaders provided by Three.js.
In the previous chapters, we looked at the various materials we can use to skin our objects. For instance, we saw how we can change the color, shininess, and opacity of these materials. What we haven’t discussed in detail yet, however, is how we can use external images (also called textures) together with these materials. With textures, we can easily create objects that look as if they are made out of wood, metal, stone, and much more. In Chapter 10, we’ll explore all the different aspects of textures and how they are used in Three.js.