Skip to content

Instantly share code, notes, and snippets.

@Breefield
Created June 18, 2011 00:29
Show Gist options
  • Save Breefield/1032655 to your computer and use it in GitHub Desktop.
Save Breefield/1032655 to your computer and use it in GitHub Desktop.
JS Animation class
var Animator = function(a, b) {
var clear_frame = true;
var current_frame = 0;
var auto_repeat = true;
var refresh_ms = 30;
var callbacks = [];
initialize(a, b);
function initialize(canvas) {
var self = this;
self.canvas = canvas;
self.ctx = canvas.getContext('2d');
}
function play() {
frame();
}
function pause() {
auto_repeat = false;
}
function addCallback(name, callback) {
callbacks.push({name: name, f: callback});
return this;
}
function removeCallback(name) {
for(var i = 0; i < callbacks.length; i++) {
var callback = callbacks[i];
if(callback.name == name) {
callbacks.splice(i, 1);
break;
}
}
return this;
}
function frame() {
var self = this;
self.canvas.width = self.canvas.width;
self.ctx.clearRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < callbacks.length; i++) {
var callback = callbacks[i];
if(typeof callback.f == 'function') callback.f(current_frame);
}
current_frame++;
if(auto_repeat) setTimeout(function() { frame(); }, refresh_ms);
}
return {
initialize: initialize,
frame: frame,
play: play,
pause: pause,
addCallback: addCallback,
removeCallback: removeCallback
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment