function animateImage(Index) {
$("img.animated:eq(" + Index + ")").each(function (Index) {
if (!$(this).is(":visible")) {
var intervalID = parseInt($(this).attr("intervalid"));
clearInterval(intervalID);
} else {
var max = parseInt($(this).attr("max"));
var pattern = $(this).attr("pattern");
var index = parseInt($(this).attr("index"));
index++;
if (index > max) {
index = 1;
}
var src = pattern.replace("#", index);
$(this).attr("index", index);
$(this).attr("src", src);
}
});
}
function initialiseAnimatedImages() {
$("img.animated").each(function (Index) {
var interval = $(this).attr("interval");
$(this).attr("index", "0");
var intervalID = setInterval(function () { animateImage(Index); }, interval);
$(this).attr("intervalid", intervalID);
});
}
$(document).ready(function () {
initialiseAnimatedImages();
});
Simply include the above script in your page(s) and where you want to specify an animated image (doesn't have to be PNG) then do the following...<img class="animated" interval="50" max="20" pattern="./images/image-sequence-#.png" />
Pattern is the image URL, but # will be replaced with a number between 1 and max. Interval is the time between changing from image 1 to 2, 2 to 3 etc. in milliseconds. So, an interval of 50 will give you about 20 frames per second. (I say "about" because browsers are not exact and they all vary slightly). Make sure the class is or includes "animated" so that the script knows to animate it. (In case you didn't know, you can mix classes, such as "myclass animated".)
The only other thing added is that if you set the image to be invisible, the animation will stop. This may sound a little odd, but your browser would still be taking up CPU animating the image, even when invisible. This avoids it.
Anyway, there was a reason that I made this (other than animated GIFs being ugly). I wanted to make a "loading" style spinner animation that you could change the colour of using CSS.
An example of this can be seen here....
http://www.johnmolyneux.co.uk/examples/loading-spinner.html