Skip to content

Instantly share code, notes, and snippets.

@hackash
Last active October 8, 2016 21:53
Show Gist options
  • Save hackash/6c450cbab7134bcb0f88dc94f36c9140 to your computer and use it in GitHub Desktop.
Save hackash/6c450cbab7134bcb0f88dc94f36c9140 to your computer and use it in GitHub Desktop.
60 frames per second (60FPS) based animation in javascript.
(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