Simple Linear Animation
by Noreh AD
HTML
<div id="box"></div>
CSS
body {
background: gainsboro;
}
#box {
width: 100px;
height: 100px;
background: white;
box-shadow: 1px 1px 1px rgba(0,0,0,.2);
position: absolute;
left: 0;
}
JavaScript
var box = document.getElementById("box");
var fps = 60;
var duration = 2; // seconds
var iterations = fps * duration; // 120 frames
var startPosition = 0; // left end of the screen
var endPosition = window.innerWidth - box.clientWidth; // right end of the screen
var distance = endPosition - startPosition; // total distance
var posIncrement = distance / iterations; // change per frame
var position = startPosition; // current position
function move() {
position += posIncrement; // increase position
if (position >= endPosition) { // check if reached endPosition
clearInterval(handler); // if so, stop interval
box.style.left = endPosition + "px"; // jump to endPosition
return; // exit function
}
box.style.left = position + "px"; // move to the new position
}
var handler = setInterval(move, 1000/fps); // run move() every 16~ millisecond