requestanimationframe实现旋转、暂停、继续
代码:
<!DOCTYPE html>
<html>
<head>
<style>
div {
position: absolute;
left: 10px;
top: 50px;
padding: auto;
color: white
}
h1 {
color: green;
}
</style>
</head>
<body>
<div id="gfg">
<h1>GeeksforGeeks</h1>
</div>
<center>
<button onclick="start()">Start the animation</button>
<button onclick="stop()">Stop the animation</button>
<button onclick="continu()">Click me to continue!</button>
</center>
<script type="text/javascript">
var x = document.getElementById("gfg");
var requestId = 0,
animationStartTime = 0,
stoppedAt = 0;
var state = 'stopped';
function animate(time) {
var current = (time - animationStartTime) / 20 % 360;
x.style.transform = 'rotate(' + current + 'deg)';
requestId = window.requestAnimationFrame(animate);
}
function start() {
state = 'rotating';
if (requestId) {
window.cancelAnimationFrame(requestId);
}
animationStartTime = window.performance.now();
requestId = window.requestAnimationFrame(animate);
}
function stop() {
if (state === 'stopped') {
return;
}
if (requestId) {
window.cancelAnimationFrame(requestId);
stoppedAt = window.performance.now();
state = 'stopped';
}
}
function continu() {
if (state === 'rotating') {
return;
}
animationStartTime += window.performance.now() - stoppedAt;
requestId = window.requestAnimationFrame(animate);
state = 'rotating';
}
</script>
</body>
</html>