user7867717
user7867717

Reputation: 283

Stop and continue animation with requestAnimationFrame

How to continue my animation at the same place that I stopped it in JavaScript ?

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. When I continue, it doesn't begin at the same place it's stopped.

Upvotes: 1

Views: 688

Answers (1)

Khalid Ali
Khalid Ali

Reputation: 1224

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>

Upvotes: 1

Related Questions