Creating sprites using javascript and CSS

The following is an animated sprite image. The concept is like every other preloaderless CSS trick. It takes one big image and shifts the background position accordingly. One advantage of this method is that it does not require a special image type. Although this image is a gif, it could be a png or a jpeg.

The image in its unanimated state. Note that the spacing between the "frames" must be consistent:

pacman sprite

The CSS

The CSS is simple to start with:

div.sprite {
	/* how big is an individual frame? */
	width: 28px;
	
	/* the whole sprite image to use */
	background-image: url(pacman.gif);
	
	/* no reason to repeat the image */
	background-repeat: no-repeat;
	
	/* the height of a frame */
	height: 29px;
}

The javascript

This gets a bit more complicated. We do a few things, first we create a set of variables which define the animation properties: frame width and frame speed.

var animationSpeed = 100;
var animationWidth = 50;

Next, we define a function that we will call in repetition that will do our animation:

function animate(id) {
	// create a temporary element
	var e = document.getElementById(id);
	
	/* 	e.pos is set later, but every element
		contains the current frame position
		it is on, it starts at 0
		
		each iteration, add appropriate offset
	*/
	e.pos += animationWidth;
	
	/* we have hardcoded the end point for our
		example.  If this were generic, this property
		should be set some place else
		
		start the animation over */
	if (e.pos > 175)
		e.pos = 0;
	
	/* set the new background position 
		we're not moving in the x direction, just the y
	*/
	e.style.backgroundPosition = -e.pos + 'px 0';
	
	// do it all over again
	setTimeout("animate('" + e.id + "')", animationSpeed);
	
}

There is only one last step: making it start up on load.

onload = function() {
	// sprites are in divs with the class of sprite
	// first get all the divs
	var sprites = document.getElementsByTagName('div');
	
	// loop over every div
	for (var i = 0, sLen = sprites.length; i < sLen; i++)
		// find the divs with a class of "sprite"
		if (sprites[i].className == 'sprite') {
			// set the initial animation location to 0
			sprites[i].pos = 0;
			
			// start the animation process
			setTimeout("animate('" + sprites[i].id + "')", animationSpeed);
		}
	
}