🔹.requestAnimationFrame()

🔰 JSbrowserDOMtypeWindow ⟩ .requestAnimationFrame()

  • run the animation

// ⭐️ 1. request first frame
requestAnimationFrame(animate);

// render loop
// - t1: current timestamp (in ms)
// - t0: last timestamp
function animate(t1, t0) {
  if (!t0) t0 = t1;
  // ⭐️ 2. update the animation ...
  // ...
  // ⭐️ 3. request next frame if necessary
  if (!done) requestAnimationFrame(t2 => animate(t2, t1));
}
  • stop the animation

let id = requestAnimationFrame(animate);
// ...
cancelAnimationFrame(id);

⭐️ 注意:

requestAnimationFrame()timestamp 是從「網頁一打開」就開始計算,並不是從執行 requestAnimationFrame(animate) 才開始

Last updated