Log

View Options

AnimatedImg - Javascript Class

4/20/11

Some time ago I had an urge to create an animated set of .png images. Well, in the fun of experimentation I went a little over board and made a full javascript class that not only animates several different types of image files, but also offers a nice set of play control methods and event listeners!

Ok, lets go over a little of how it works, shall we? First lets create a simple animation of a ball bouncing using. There are only three basics things we need here. One, an array of image files. Two make sure my animatedImg class is included. Three, make a call to the passing in the array, so this;

Snipt.net is dead - replace code sample from: "http://snipt.net/embed/43547100f4e6b5dc03399183e335d5c2"

Makes this

Animation Type

Notice how ball one appears to be only playing half of the animation while ball two bounces smoothly up and down. The set of images we have passed to our AnimatedImg object is in fact only half a ball bounce. When creating an AnimatedImg you can dictate how it plays from the start. there are 7 types, and they are referenced through a 0 index array. The values are; 0 = "stopped", 1 = "playOnce", 2 = "repeat", 3 = "playBackwardOnce", 4 = "playBackwardRepeat", 5 = "forwardBackwardOnce", 6 = "forwardBackwardRepeat".

Methods and Events

Now for the exciting stuff adding interaction to your AnimatedImg. For this example I dug up an old favorite, Chance the original character from my old Skate-er-Guy game. Click on him and he'll do a hard flip for you. Click on him again and he'll reverse his play direction! Anyways, here is the code used to make the skater interaction.

There is some slight buggyness with mouse based events I'm trying to work out. Currently, the mouse events stand a chance of not registering from what I believe is the click happening as the image is changing frames, thus the AnimatedImg has no clickable area for that brief instance.

Well I'm not into super gigantic posts so I'll cut to the chase, if you would like to use this class for a personal project or to just play with feel free to DOWNLOAD THE EXAMPLE PACKAGE.