Created
September 14, 2012 22:46
-
-
Save ipetepete/3725447 to your computer and use it in GitHub Desktop.
Sparkli sprite animator plugin for jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($){ | |
$.fn.sparkli = function( opts ){ | |
options = { | |
spriteWidth: null, | |
spriteHeight: null, | |
spritePadding: 0, | |
rows : 1, | |
cols : 10, | |
totalSprites : 0, | |
framesPerSecond: 20, | |
target: this, | |
trigger: "click", | |
sound : { | |
// sound files should be listed in order of file size in ascending order | |
// first one that works will be used. | |
// mp3 file should be provided to support older (IE) browsers | |
}, | |
debug : false | |
}; | |
var settings = $.extend(options, opts); | |
// load the sound | |
if( $.isEmptyObject(settings.sound) === false){ | |
if( Modernizr.audio){ | |
for(var i in settings.sound){ | |
if(Modernizr.audio[i]){ | |
window.sparkli_sound = new Audio(); | |
window.sparkli_sound.setAttribute("src", settings.sound[i]); | |
break; | |
} | |
} | |
}else{ | |
// no HTML5 audio support | |
if($("#HTML4_sparkli_sound").length === 0){ | |
if( settings.sound.mp3 ) | |
$("body").append("<embed src='"+settings.sound.mp3+"'"+ | |
"autostart=false width=1 height=1 "+ | |
"id='HTML4_sparkli_sound' "+ | |
"enablejavascript='true'>"); | |
} | |
} | |
} | |
playSound = function(){ | |
// drop out if we don't have any sound to play | |
if( settings.sound.length === 0){ | |
return void(0); | |
} | |
if( window.sparkli_sound ){ | |
window.sparkli_sound.play(); | |
return void(0); | |
} | |
try{ | |
$("#HTML4_sparkli_sound")[0].Play(); | |
}catch(e){ | |
// no sound :( | |
} | |
} | |
return this.each(function(){ | |
var self = this; | |
$(settings.target).on(settings.trigger, function(){ | |
$(self).show();//css("display", "inline-block"); | |
var delay = 0; | |
var count = 0; | |
playSound(); | |
for(var y = 0; y < settings.rows; y++ ) { | |
for (var x = 0; x < settings.cols; x++) { | |
var posX = x*settings.spriteWidth + settings.spritePadding + (x*settings.spritePadding); | |
var posY = y*settings.spriteHeight + settings.spritePadding + (y*settings.spritePadding); | |
delay += (1000/settings.framesPerSecond); | |
count += 1; | |
// timeout closure, preserve x,y | |
(function(x,y, delay, iteration, lastsprite){ | |
setTimeout(function(){ | |
if( settings.debug ){ | |
console.log("X pos:"+x+" Y pos: "+y+" iteration: "+iteration); | |
console.log("last ", lastsprite); | |
} | |
$(self).css("background-position", (-x)+"px "+(-y)+"px"); | |
if(lastsprite){ | |
$(self).hide(); | |
} | |
}, delay); | |
})(posX, posY, delay, x, count >= settings.totalSprites); | |
} | |
} | |
}) | |
}); | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment