简体   繁体   English

使用 requestAnimationFrame 停止并继续 animation

[英]Stop and continue animation with requestAnimationFrame

How to continue my animation at the same place that I stopped it in JavaScript?如何在我在 JavaScript 中停止它的同一个地方继续我的 animation?

Code:代码:

 var requestId = 0; function animate(time) { document.getElementById("animated").style.left = (time - animationStartTime) % 2000 / 4 + "px"; requestId = window.requestAnimationFrame(animate); } function start() { animationStartTime = window.performance.now(); requestId = window.requestAnimationFrame(animate); } function stop() { if (requestId) window.cancelAnimationFrame(requestId); requestId = 0; } function continu() { requestId = window.requestAnimationFrame(animate); }
 #animated { position: absolute; left: 10px; padding: 50px; background: crimson; color: white; margin-top: 50px; }
 <button onclick="start()">Click me to start.</button> <button onclick="stop()">Click me to stop!</button> <button onclick="continu()">Click me to continu!</button> <div id="animated">Hello there.</div>

First I start the animation, then I stop it, and then I continue it.首先我启动 animation,然后我停止它,然后我继续它。 When I continue, it doesn't begin at the same place it's stopped.当我继续时,它不会从它停止的同一个地方开始。

You have to take the stoppage time into count.您必须将补时时间考虑在内。

Here's the solution:这是解决方案:

 var requestId = 0, animationStartTime = 0, stoppedAt = 0; function animate(time) { document.getElementById("animated").style.left = (time - animationStartTime) % 2000 / 4 + "px"; requestId = window.requestAnimationFrame(animate); } function start() { animationStartTime = window.performance.now(); requestId = window.requestAnimationFrame(animate); } function stop() { if (requestId) { window.cancelAnimationFrame(requestId); // Stop point timestamp stoppedAt = window.performance.now(); } } function continu() { // Adding stoppage time to start time. animationStartTime += window.performance.now() - stoppedAt; requestId = window.requestAnimationFrame(animate); }
 #animated { position: absolute; left: 10px; padding: 50px; background: crimson; color: white; margin-top: 50px; }
 <button onclick="start()">Click me to start.</button> <button onclick="stop()">Click me to stop!</button> <button onclick="continu()">Click me to continue!</button> <div id="animated">Hello there.</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM