Stupid Web Tricks: JavaScript PNG Sprite Explosions

Sprite animation: A technique that existed back in the 1970s can also be easily implemented with JavaScript on the Web in the 21st Century...

Click the image below to see the animation
The images to the right compose the three layers you see above. These are controlled by the z-index in the stylesheet.

With the PNG transparency bug in IE worked around, and JS libraries like YUI and prototype.js, it's almost trivial for any web developer to develop cool-looking sprite animations.

The code is pretty simple:

for(var y = -192; y <= 0; y+=64 ) {
    for (var x = -192; x <= 0; x+= 64) {
        var left = x + parentCoord[0];
        var top = y + parentCoord[1];
        setTimeout("YD.setXY('" + id + "',[" + left + "," + top + "])", delay);
        delay += 20;

Here, parentCoord is an array holding the top/left positions of the <div> that contains the image of the explosion, which is the offset that's needed for the explosion <img> element. The YD object is just an alias to YAHOO.util.Dom.

If you view source, you'll see that I also animate going the other way so there's a fade-in/fade-out technique.

Of course, it becomes much easier if the explosion image were one long "filmstrip," instead of a grid, which saves you the expense of writing two for loops.

The other interesting thing is that you can do this with background images in the div using background-position in the CSS, however the PNG transparency hack for IE can act a bit wonky that way.

You may also be so clever as to putting all three images into one single PNG, and then positioning them in each box so they appear as separate images. This is a well-known, (and hopefully fast-growing) technique that helps to reduce the number of HTTP requests made to fetch stuff. AKA, instead of one request for every image, just get all the "images" with one HTTP request. I was too lazy to do that for this demo.

Cannon image photo (cc) David Wiley. Some rights reserved. Used under Creative Commons Attribution 2.0 license.