Play animations on the canvas element

Play animations on the canvas element
Page content

An animation is simply a sequence of images, or frames, that are drawn in succession to create a moving image. We already know how to display static images (and move them around on the screen), so displaying an animation is not a big leap.

First we need the images that will make up the animation. I found a very nice selection of animated sprites on The Protagonist’s Domain. The images are reminiscent of the old Metal Slug games, and will suit our platformer game quite nicely.

The first step is getting the animated sprites into a format that can be easily used with JavaScript and the canvas element. You will notice that the images over on the The Protagonist’s Domain are all animated GIF files. Rather than use the animated gif file, we want to work with a single “film strip” image. This is because it is very easy to draw only a small section of an image to the canvas, which allows us to select each frame from an image containing all the frames.

So how do we take an aimated GIF image and convert it into the single film strip image that we need? I had a quick look on the net for a tool that would do this automatically, but in the end I used a program called GIF Movie Gear. When you open up the animated GIF image, Movie Gear shows the film strip in it’s main window. By doing a print screen and modifying the image in Paint.NET I found I could get the desired result.

Movie Gear

With the film strip image in hand it’s time to create a class that can display this animation onto the canvas element.

AnimatedGameObject.js

AnimatedGameObject (an Engine class) extends the VisualGameObject class. It adds a number of properties that are needed to play an animation. [code]

currentFrame Defines the current frame that is to be rendered

frameWidth The width of each individual frame

timeBetweenFrames Defines the frames per second of the animation

timeSinceLastFrame Time until the next frame

In addition the draw function has been modified to only draw a subset of the source image (the current frame) to the canvas element, while incrementing the currentFrame property over time to create the animation. [code]

Check out the demo here, download the source code here, and browse the code documentation here.

Read more in the Game Development with JavaScript and the Canvas element series.