Sprite Animation

by Reiot

HTML

<div id="airborne"></div>

CSS

#airborne {
    position: absolute;
    top: 100px;
    left: 100px;
    width: 128px;
    height: 168px;
    background: transparent url(http://reiot.dyndns.org:8080/images/test/airborne.png) 0 0 no-repeat;
}

JavaScript

$(function() {
    
    var warcloud = {};
    warcloud.animate = function(div){
        var ani = div.data('ani');
        ani.index++;
        if(ani.index==ani.frames.length){
            ani.index=0;//infinite
        }
        console.log('animate!',ani.index,ani.frames[ani.index]);
        div.css(ani.frames[ani.index]);
    };
    warcloud.sprites = [];
    warcloud.aniTimer = window.setInterval(function(){
        for(var i=0,len=warcloud.sprites.length;i<len;i++){
            var $sprite = warcloud.sprites[i];
            if($sprite.length){
                warcloud.animate($sprite);
            }else{
                console.warn('remove this');
            }
        }
    },1000/3);
        
    $.fn.ani = function(opts) {
        var options = $.extend({
            index: 0
        },opts);

        console.log('options',options);

        return this.each(function(){
            var $this = $(this);
            $this
                .data('ani', options)
                .css(options.base);
            
            // if not exist
            if( $.inArray(warcloud.sprites, $this) < 0 ) {
                warcloud.sprites.push($this);
            } 
        });
    };
    
    var walkLeft = {
        name: 'walk-left',
        base: {
            width: '128px',
            height: '168px',
            background: 'transparent url(http://reiot.dyndns.org:8080/images/test/airborne.png) 0 0 no-repeat'
        },
        frames: [
            {backgroundPosition: '0 0'},
            {backgroundPosition: '-128px 0'},
            {backgroundPosition: '-256px 0'}
        ],
        fps: 3
    },
    walkRight = {
        name: 'walk-left',
        base: {
            width: '128px',
            height: '168px',
            background: 'transparent url(http://reiot.dyndns.org:8080/images/test/airborne.png) -384px 0 no-repeat'
        },
        frames: [
            {backgroundPosition: '-384px 0'},
            {backgroundPosition: '-512px 0'},
           ...