«

»

Feb 11

Javascript with CSS Sprites Animation

One of the issues with gif animations is being able to stop and start them at will.  This post examines a method of using javascript to control CSS Sprites for Animation.

We’re going to show how one can create the following animation using javascript and sprites and what benefits you might receive:

Animated Gif

Animated Gif

The gist of this method is to use css background images, which are swapped out via javascript to show and control the animation.  In a filesize test using an animation with 9 frames, the sprites actually require less memory than a comparable animated gif:

File Size Description
Individual frames as separate PNG’s 95421 Baseline — this is the sum of the sizes of the 9 frame files.
anim.gif 43463 Animated gif version
knot.png 81701 24 bit PNG, sprites. Notice that this is smaller than the sum of the 9 files, but quite larger than the animated gif.
knot-grey.png 49708 Greyscale version of the png sprites. This is much smaller and approaches the size of the gif animation.
knot.gif 40853 Gif version of the sprites. This is smaller than the anmated version.
knot-idx.png 38281 Indexed version of the png sprites. Smallest yet.

I think that between the added control, decreased number of files to download (a single file containing sprites can be used in many places), and the potential for reduced file size, that this is a viable method for producing animations.

The javascript code is library agnostic.  Had I tied it to one library or another, I could have made it shorter, but I think that the benefits of being agnostic outweigh the potential byte savings.

Sample CSS looks like this:

Here’s the javascript source file:
sprite-animator

3 comments

  1. Thank you

    Thanks for this, was very helpful 🙂

  2. Zach

    Hey this page is EXACTLY what I’m looking for!!! I wan’t to do some Super Mario Bros. animations for my website selling super mario brothers toys and games, would you be able to help me a bit further with a project, I was having some trouble interpreting your code, as I’m a total n00b, but I’d love to have some help, as this is just what I need!

    Thanks!!

  3. Louise Lambert

    Great site. Keep up the good work.

Leave a Reply

%d bloggers like this: