Skip to content

Instantly share code, notes, and snippets.

@baniol
Created March 29, 2014 09:41
Show Gist options
  • Save baniol/9851512 to your computer and use it in GitHub Desktop.
Save baniol/9851512 to your computer and use it in GitHub Desktop.
basic animation, javascript requestAnimationFrame
<html>
<head>
<style type="text/css">
#anim {
position:absolute;
left:0px;
width:150px;
height:150px;
background: blue;
font-size: larger;
color: white;
border-radius: 10px;
padding: 1em;
}
</style>
</head>
<body>
<div id="anim">Click here to start animation</div>
<script type ="application/javascript" language="javascript">
// shim layer with setTimeout fallback
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
var elem = document.getElementById("anim");
var startTime = undefined;
function render(time) {
if (time === undefined)
time = Date.now();
if (startTime === undefined)
startTime = time;
elem.style.left = ((time - startTime) / 10 % 500) + "px";
}
elem.onclick = function() {
(function animloop() {
render();
requestAnimFrame(animloop, elem);
})();
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment