Basic animations

Since we're using JavaScript to control <canvas> elements, it's also very easy to make (interactive) animations. Doing more complex animations can take a little extra work; we hope to introduce a new article to help with that soon.

Probably the biggest limitation is that once a shape gets drawn it stays that way. If we need to move it we have to redraw it and everything that was drawn before it. It takes a lot of time to redraw complex frames and the performance depends highly on the speed of the computer it's running on.

Basic animation steps

These are the steps you need to take to draw a frame:

Clear the canvas
Unless the shapes you'll be drawing fill the complete canvas (for instance a backdrop image), you need to clear any shapes that have been drawn previously. The easiest way to do this is using the clearRect() method.

Save the canvas state
If you're changing any setting (such as styles, transformations, etc) which affect the canvas state and you want to make sure the original state is used each time a frame is drawn, you need to save that original state.

Draw animated shapes
The step where you do the actual frame rendering.

Restore the canvas state
If you've saved the state, restore it before drawing a new frame.

Controlling an animation

Shapes are drawn to the canvas by using the canvas methods directly or by calling custom functions. In normal circumstances, we only see these results appear on the canvas when the script finishes executing. For instance, it isn't possible to do an animation from within a for loop.

That means we need a way to execute our drawing functions over a period of time. There are two ways to control an animation like this.

If you don't want any user interaction it's best to use the setInterval() function which repeatedly executes the supplied code.

Updating on user interaction

The second method we can use to control an animation is user input. If we wanted to make a game, we could use keyboard or mouse events to control the animation. By setting EventListeners, we catch any user interaction and execute our animation functions.