Last active
September 30, 2019 06:26
-
-
Save gujc71/a4e79744668467b297bb7811ea632fe5 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Script-based animation using requestAnimationFrame</title> | |
<style type="text/css"> | |
div { | |
position: absolute; | |
left: 10px; | |
top:100px; | |
padding: 50px; | |
background: crimson; | |
color: white; | |
} | |
</style> | |
<script type="text/javascript"> | |
//https://msdn.microsoft.com/ko-kr/library/hh920765(v=vs.85).aspx | |
var requestId = 0; | |
var lpos = 0; | |
var elm; | |
function init() { | |
elm = document.getElementById("animated"); | |
} | |
function render() { | |
elm.style.left = ((lpos += 3) % 600) + "px"; | |
} | |
var dt = 0, step = 0.4; | |
var last = now = timestamp(); | |
function timestamp() { return new Date().getTime(); } | |
function frame() { | |
now = timestamp(); | |
update(Math.min(1, (now - last) / 1000.0)); | |
last = now; | |
requestId = window.requestAFrame(frame); | |
} | |
function update(idt) { | |
dt = dt + idt; | |
if (dt > step) { | |
dt = dt - step; | |
render(); | |
} | |
} | |
function speedUp() { | |
step -= 0.05 | |
if (step < 0.1) step = 0.1; | |
} | |
function start() { | |
frame() | |
} | |
function stop() { | |
if (requestId) | |
window.cancelAFrame(requestId); | |
} | |
window.requestAFrame = (function () { | |
return window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
window.oRequestAnimationFrame || | |
function (callback) { | |
return window.setTimeout(callback, 1000 / 60); // shoot for 60 fps | |
}; | |
})(); | |
window.cancelAFrame = (function () { | |
return window.cancelAnimationFrame || | |
window.webkitCancelAnimationFrame || | |
window.mozCancelAnimationFrame || | |
window.oCancelAnimationFrame || | |
function (id) { | |
window.clearTimeout(id); | |
}; | |
})(); | |
</script> | |
</head> | |
<body onload="init();"> | |
<div id="animated">Hello there.</div> | |
<button onclick="start()">Start</button> | |
<button onclick="stop()">Stop</button> | |
<button onclick="speedUp()">Speed Up</button> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment