Setting up an animation loop
In the recipes at the beginning of this chapter, we showed you how to set up a basic Three.js scene, using one of the available renderers. If you want to add animations to your Three.js scene, for instance, to move the camera around or rotate an object, you'll need to call the render
function multiple times. In the old days of JavaScript, you had to control this yourself using the setTimeout
or setInterval
JavaScript functions. The problem with these functions is that they don't take into account what is happening in your browser. For instance, your page will be hidden or the Three.js scene might be scrolled out of view. A better solution for animations, and the one that we'll use in this recipe, is requestAnimationFrame
. With this function, your browser determines when it is the best time to call the animation code.
Getting ready
For this recipe, we will use the 01.05-setup-animation-loop.html
example HTML file. To see the animation in action, just open this file in your browser:
This example uses the WebGL renderer. You can of course apply this same recipe to the other renderers we've discussed in this chapter.
Let's take a look at the steps we need to take to set up such an animation loop.
How to do it...
To create an animation loop you don't have to change much in your existing code:
- Let's first look at how to use
requestAnimationFrame
for rendering. For this, we've created a render function:function render() { renderer.render(scene, camera); scene.getObjectByName('cube').rotation.x += 0.05; requestAnimationFrame(render); }
As you can see, we pass the render function as an argument to request a frame for animation. This will cause the
render
function to be called at a regular interval. In therender
function, we will also update the rotation of the x axis of the cube to show you that the scene is re-rendered. - To use this function in the recipes, which we saw at the beginning of this chapter, we just have to replace this call:
function init() { ... // call the render function renderer.render(scene, camera); } With the following: function init() { ... // call the render function render(); }
- You will now have your own animation loop, so any changes made to your model, camera, or other objects in the scene can now be done from within the
render()
function.
See also
- We mentioned that in this recipe, we've used the
THREE.WebGLRenderer
object as an example. You can of course also apply this to the skeletons from the Getting started with the Canvas renderer recipe or Getting started with the CSS 3D renderer recipe. - What will be of interest to you also is the Determining the frame rate of your scene recipe, where we'll add additional functionality to the skeletons so you can easily see how often the render function is called by
requestAnimationFrame
.