// *** Dependency *** //
var Loop=new Class({loopCount:0,isStopped:true,isLooping:false,loopMethod:$empty,setLoop:function(fn,delay){if(this.isLooping)this.stopLoop();this.loopMethod=fn;this.loopDelay=delay||3000;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;}});
// *** THE CLASS *** //
var SpriteAnimation=new Class({Implements:[Options,Events,Loop],options:{frameWidth:75,frames:10,frameRate:100},initialize:function(element,options){this.setOptions(options);this.setLoop(this.step,100);this.element=document.id(element);this.startLoop();},step:function(){this.loopCount=(this.loopCount==(this.options.frames))?0:this.loopCount;var style=-this.loopCount*this.options.frameWidth;this.element.setStyle('background-position',style+'px 0px');this.fireEvent('onStep',this.count);return this;},reset:function(){this.loopCount=this.options.frames;this.step();return this;}});SpriteAnimation.implement({loop:function(loops){var c=0;loops=loops*this.options.frames;if(this.isStopped)this.startLoop();this.addEvents({onStep:function(step){c++;if(c==loops)this.stopLoop();}});}});
// *** USAGE *** //
window.addEvent('domready',function(){
var animation = new SpriteAnimation('animation',{
frameWidth: 80,
frames: 4,
frameRate: 120
});
// *** TEST *** //
$('start_stop').addEvent('click',function(){
if(this.get('text') == 'Stop') {
animation.stopLoop();
this.set('text','Start');
} else {
animation.startLoop();
this.set('text','Stop');
}
});
$('loop').addEvent('click',function(){
animation.loop($('loops').value);
});
$('reset').addEvent('click',function(){
animation.reset();
});
});
<div id="demo">
<h2>Demo</h2>
<div id="animation"></div>
<p>
<button id="start_stop">Stop</button>
<button id="reset">Reset</button>
</p>
<p>
<button id="loop">Loop</button> <input type="text" id="loops" value="1" size="3" /> times
</p>
</div>
<div id="sprite">
<h2>The sprite</h2>
<p>
<img src="http://ryanflorence.com/animation.png" />
</p>
</div>
#animation {
height: 160px;
width: 80px;
background-image: url(http://ryanflorence.com/animation.png);
background-repeat: no-repeat;
background-position: 0 0;
}
body {
font-family: Helvetica, arial;
background: #fff;
}
h2 {
color: #43aa38;
margin-bottom: 1em;
}
div#demo {
float: left;
}
div#sprite {
float: left;
}
div#sprite img {
height: 75px;
}