Skip to content

Instantly share code, notes, and snippets.

@davidhellsing
Last active December 20, 2015 13:39
Show Gist options
  • Save davidhellsing/6140433 to your computer and use it in GitHub Desktop.
Save davidhellsing/6140433 to your computer and use it in GitHub Desktop.
Animate anything with easing and requestFrame.
Animate = (function() {
var requestFrame = (function(){
var r = 'RequestAnimationFrame'
return window.requestAnimationFrame ||
window['webkit'+r] ||
window['moz'+r] ||
window['o'+r] ||
window['ms'+r] ||
function( callback ) {
window.setTimeout(callback, 1000 / 60)
}
}())
var animations = {}
;(function animloop() {
requestFrame(animloop)
for ( var i in animations ) {
anim( animations[i] )
}
}())
function anim(obj) {
var dist = obj.to - obj.val
if ( Math.abs(dist) <= obj.threshold ) {
obj.step.call(obj, obj.to )
if ( typeof obj.complete == 'function' ) {
obj.complete.call(obj)
}
delete animations[ obj.id ]
return
}
obj.val = obj.easing(null, obj.timer++, obj.val, dist, obj.duration)
obj.step.call( obj, obj.val )
}
return function(obj) {
if (
!obj.hasOwnProperty('from') ||
!obj.hasOwnProperty('to') ||
!obj.hasOwnProperty('step')
) { throw new SyntaxError('From, To & Step required') }
obj.val = obj.from
obj.timer = 0
obj.id = +new Date()
obj.duration = obj.duration || 400
obj.easing = obj.easing || function(x,t,b,c,d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b // easeOutQuart
}
obj.threshold = obj.threshold || Math.abs(obj.to-obj.from)/100
console.log(obj);
animations[ obj.id ] = obj
}
}())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment