Created
May 6, 2016 08:55
-
-
Save Sambego/085fa4d1e91b32e5911f63465d37ecd2 to your computer and use it in GitHub Desktop.
Animation function
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
/* | |
* A simple function to animate a property of an element to a new value. | |
*/ | |
const animate = function animate(element, property, value, duration) { | |
const fps = 60; | |
const timeout = duration / (1000 / fps); | |
const startTime = new Date(); | |
const startValue = element[property]; | |
const step = function step() { | |
const currentTime = new Date(); | |
const passedTime = currentTime.getTime() - startTime.getTime(); | |
const passedTimeRatio = (passedTime / duration) > 1 ? 1 : (passedTime / duration); | |
const currentValue = (startValue + ((value - startValue) * passedTimeRatio)); | |
element[property] = currentValue; | |
if (passedTime < duration) { | |
window.setTimeout(() => { | |
window.requestAnimationFrame(step); | |
}, timeout); | |
} | |
}; | |
window.requestAnimationFrame(step); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment