Skip to content

Instantly share code, notes, and snippets.

@yusugomori
Last active December 15, 2015 03:19
Show Gist options
  • Select an option

  • Save yusugomori/5193969 to your computer and use it in GitHub Desktop.

Select an option

Save yusugomori/5193969 to your computer and use it in GitHub Desktop.
// Flashless animation with stop motion images
// html: <img id="img" />
/* Preload */
var preload = function(path){
var dfd = $.Deferred();
var img = document.createElement('img');
img.src = path;
img.addEventListener('load', function(){
dfd.resolve();
}, false);
img.onerror = function(){
dfd.reject();
};
return dfd.promise();
};
/* Animate */
var animate = function($img, imgs, i, refreshRate){
if(i >= imgs.length) return;
setTimeout(function() {
$img.attr('src', imgs[i]);
animate($img, imgs, i+1, refreshRate);
}, refreshRate);
};
var $img = $('#img');
var imgs = [];
for(var i=0; i<100; i++) imgs.push('/path/to/imgs/'+i+'.png');
var dfds = [];
for(var i=0; i<imgs.length; i++) dfds.push( preload(imgs[i]) );
$.when.apply(null, dfds).done(function(){
var refreshRate = 200;
animate($img, imgs, 0, refreshRate);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment