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.
With the film strip image in hand it's time to create a class that can display this animation onto the canvas element.
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.