User friendly easing with caching
by pajtai
HTML
<div id="box"></div>
CSS
#box {
width: 100px;
height: 100px;
margin-left:0;
background-color:blue;
}
body: {
width:100%;
}
JavaScript
(function(window) {
var r = 0, g = 1, b = 2,
document = window.document,
box = document.getElementById('box'),
easing = {
// normalized easing equation with caching
easeInOutSine: (function () {
var cache = {};
// return the normalized easing equation to the animation
return function(t) {
// If result is not in the cache, then put it in
if (! cache[t]) {
cache[t] = -1/2 * (Math.cos(Math.PI*t) - 1)
}
return cache[t];
};
}())
},
// make smart use of the browsers animation frame if available
// default to 60fps if not
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimationFrame = (function () {
return (window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
this.setTimeout(callback, 1000 / 60);
}).bind(window);
})(),
// The animation equation with user friendly argument
// This will take care of normalization before calling the easing equation,
// * tickHook - function that get called on each tick with the updated number
// * startNum - initial value
// * endNum - final value
// * duration - how long animation last in milliseconds
// * callback - (optional) function to call when animation finishes
// * easingEq - (optional) easing equation
animate = function(tickHook, startNum, endNum, duration, callback, easingEq) {
var easingEq = easingEq || easing.easeInOutSine,
changeInNum = endNum - startNum,
startTime = new Date().getTime(),
...