Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created May 9, 2010 14:46
Show Gist options
  • Save ryanflorence/395197 to your computer and use it in GitHub Desktop.
Save ryanflorence/395197 to your computer and use it in GitHub Desktop.
var Loop = new Class({
loopCount: 0,
isStopped: true,
isLooping: false,
loopMethod: $empty,
setLoop: function(fn, delay){
if(this.isLooping) {
this.stopLoop();
var wasLooping = true;
} else {
var wasLooping = false;
}
this.loopMethod = fn;
this.loopDelay = delay || 3000;
if(wasLooping) this.startLoop();
return this;
},
stopLoop: function() {
this.isStopped = true;
this.isLooping = false;
$clear(this.periodical);
return this;
},
startLoop: function(delay) {
if(this.isStopped){
var delay = (delay) ? delay : this.loopDelay;
this.isStopped = false;
this.isLooping = true;
this.periodical = this.looper.periodical(delay,this);
};
return this;
},
resetLoop: function(){
this.loopCount = 0;
return this;
},
looper: function(){
this.loopCount++;
this.loopMethod(this.loopCount);
return this;
}
});
var SpriteAnimation = new Class({
Implements: [Options, Events, Loop],
options: {
frameWidth: 75,
frames: 10,
frameRate: 100,
defaultPosition: {x: 0, y :0}
},
jQuery: 'spriteAnimation',
initialize: function(selector, options){
this.setOptions(options);
this.setLoop(this.step, this.options.frameRate);
this.element = jQuery(selector);
var pos = this.options.defaultPosition.x + 'px ' + this.options.defaultPosition.y + 'px';
this.element.css({'background-position': pos});
this.startLoop();
},
step: function(){
var x = this.computeX();
var y = this.computeY();
this.element.css({'background-position': x+'px '+ y+'px'});
return this;
},
computeX: function(){
this.loopCount = (this.loopCount == (this.options.frames)) ? this.options.defaultPosition.x : this.loopCount
return -this.loopCount * this.options.frameWidth;
},
computeY: function(){
return this.options.defaultPosition.y;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment