Skip to content

Instantly share code, notes, and snippets.

@markbiek
Created July 15, 2011 16:19
Show Gist options
  • Save markbiek/1085004 to your computer and use it in GitHub Desktop.
Save markbiek/1085004 to your computer and use it in GitHub Desktop.
jQuery Plugin to animate a series of images using the HTML canvas element
(function( $ ){
$.fn.canvasAnimate = function(options) {
return this.each( function() {
Number.prototype.zeroPad = function() {
var i = this;
if(i < 10) {
return '0000'+i;
}else if(i >= 10 && i < 100) {
return '000'+i;
}else if(i >= 100 && i < 1000) {
return '00'+i;
}
};
var settings = {
path: '',
prefix: '',
ext: '.png',
loop: false,
speed: 40,
cur: 0,
max: 0,
loading: 0,
images: [],
intervalId: 0,
loaded: function() { },
frame: function() { }
};
if(options) {
$.extend(settings, options);
}
var canvas=this;
var ctx=canvas.getContext('2d');
for(i=0; i<settings.max-1; i++) {
var img = new Image();
img.src = settings.path + '/' + settings.prefix + i.zeroPad() + settings.ext;
img.onload = function() {
try {
settings.loading++;
if(settings.loading == (settings.max-1)) {
if(typeof settings.loaded == 'function'){ settings.loaded(); }
}
}catch(e){ alert(e.message); }
};
settings.images.push(img);
}
settings.loaded = function() {
settings.intervalId = setInterval(function() {
if(typeof settings.frame == 'function') { settings.frame(settings.cur); }
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(settings.images[settings.cur], 0, 0);
settings.cur++;
if(settings.cur >= settings.max-1) {
if(settings.loop) {
settings.cur = 0;
}else {
clearInterval(settings.intervalId);
}
}
}, settings.speed);
};
}); //return this.each
}; //$.fn.canvasAnimate
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment