Last active
October 8, 2016 21:53
-
-
Save hackash/6c450cbab7134bcb0f88dc94f36c9140 to your computer and use it in GitHub Desktop.
60 frames per second (60FPS) based animation in javascript.
This file contains hidden or 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
(function () { | |
var config = { | |
elem: document.querySelector('.moveable'), // absolute or relative positioned DOM node | |
states: [], | |
speed: 2, // pixel per frame | |
loop: true, | |
target: { | |
from: 0, | |
to: 500 | |
} | |
}; | |
function getParsedValue() { | |
return parseFloat(this.style.left) || 0; | |
} | |
function toRight() { | |
var val = getParsedValue.call(this); | |
if (val < config.target.to) { | |
this.style.left = (val + config.speed) + 'px'; | |
return false; | |
} | |
config.states.pop(); | |
config.states.push(toLeft); | |
} | |
function toLeft() { | |
var val = getParsedValue.call(this); | |
if (val > config.target.from) { | |
this.style.left = (val - config.speed) + 'px'; | |
return false; | |
} | |
config.states.pop(); | |
if (config.loop) { | |
config.states.push(toRight); | |
} | |
} | |
function animationLoop() { | |
if (config.states.length > 0) { | |
var i = 0; | |
for (; i < config.states.length; i++) { | |
config.states[i].call(config.elem); | |
} | |
} | |
requestAnimationFrame(animationLoop); | |
} | |
config.states.push(toRight); | |
animationLoop(); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment