Created
July 11, 2012 01:14
-
-
Save kinka/3087282 to your computer and use it in GitHub Desktop.
javascript animation helper learned from a book named HTML5 Games
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
window.requestAnimationFrame = (function() { | |
return window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
function(callback, element) { | |
window.setTimeout(callback, 1000/60); | |
}; | |
})(); | |
window.cancelRequestAnimationFrame = (function() { | |
return window.cancelRequestAnimationFrame || | |
window.webkitCancelRequestAnimationFrame || | |
window.mozCancelRequestAnimationFrame || | |
window.clearTimeout | |
})(); | |
var animations = [], | |
previousCycle; | |
previousCycle = Date.now(); | |
requestAnimationFrame(cycle); // begin animations | |
function cycle(time) { | |
renderAnimations(time, previousCycle); | |
previousCycle = time; | |
requestAnimationFrame(cycle); | |
} | |
function addAnimation(runTime, fncs) { | |
/* | |
@runTime: the time you hope animations holds (ms) | |
@fncs: { before: function() {}, render: function() {}, done: function() {} } | |
the function 'before' and 'done' is optional and called only once, | |
render your code in function 'render' | |
*/ | |
var anim = { | |
runTime: runTime, | |
startTime: Date.now(), | |
pos: 0, | |
fncs: fncs | |
}; | |
animations.push(anim); | |
} | |
function renderAnimations(time, lastTime) { | |
var anims = animations.slice(0), // copy list | |
n = anims.length, | |
animTime, | |
anim, | |
i; | |
// call before() function | |
for(i=0; i<n; i++) { | |
anim = anims[i]; // a reference to anims[i] | |
if(anim.fncs.before) { | |
anim.fncs.before(anim.pos); | |
anim.fncs.before = null; | |
} | |
anim.lastPos = anim.pos; | |
animTime = (lastTime - anim.startTime); | |
anim.pos = animTime / anim.runTime; | |
anim.pos = Math.max(0, Math.min(1, anim.pos)); | |
} | |
animations = []; // render animation list | |
for(i=0; i<n; i++) { | |
anim = anims[i]; | |
anim.fncs.render(anim.pos, anim.pos-anim.lastPos); | |
if(anim.pos == 1) { | |
if(anim.fncs.done) // done! | |
anim.fncs.done(); | |
} else { | |
animations.push(anim); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment