萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 動畫實現原理深度解析:從 setInterval 到 requestAnimationFrame 的演進

動畫本質:離散幀的連續幻覺

目標:將元素寬度從 100px 動畫至 200px,歷時 1000ms。

版本一:累加法 (Naïve setInterval)

function animate1(element, endValue, duration) {
  var startTime = new Date(), startValue = parseInt(element.style.width), step = 1;
  var timerId = setInterval(function() {
    var nextValue = parseInt(element.style.width) + step;
    element.style.width = nextValue + 'px';
    if (nextValue >= endValue) {
      clearInterval(timerId);
      element.innerHTML = new Date - startTime; // 顯示實際耗時
    }
  }, duration / (endValue - startValue) * step);
}
animate1(document.getElementById('test1'), 200, 1000);

缺陷:setInterval 不保證精確間隔,瀏覽器最小間隔 ~4ms、標籤頁背景節流、系統負載影響,導致實際耗時 ~1500ms (目標 1000ms)。

版本二:時間基準插值 (Time-based Interpolation)

function animate2(element, endValue, duration) {
  var startTime = new Date(), startValue = parseInt(element.style.width);
  var timerId = setInterval(function() {
    var percentage = (new Date - startTime) / duration;
    var stepValue = startValue + (endValue - startValue) * percentage;
    element.style.width = stepValue + 'px';
    if (percentage >= 1) {
      clearInterval(timerId);
      element.innerHTML = new Date - startTime;
    }
  }, 13); // 約 75fps,配合螢幕刷新率
}
animate2(document.getElementById('test2'), 200, 1000);

改進:根據經過時間計算進度,動畫時長固定,不受幀率波動影響。誤差縮減至 ~10-20ms。

版本三:邊界修正與精度保護

function animate3(element, endValue, duration) {
  var startTime = new Date(), startValue = parseInt(element.style.width);
  var timerId = setInterval(function() {
    var percentage = Math.min(1, (new Date - startTime) / duration); // 夾擋上限 1
    var stepValue = (percentage >= 1) ? endValue : startValue + (endValue - startValue) * percentage;
    element.style.width = stepValue + 'px';
    if (percentage >= 1) {
      clearInterval(timerId);
      element.innerHTML = new Date - startTime;
    }
  }, 13);
}

兩大修正:

  1. Math.min(1, ...) 防止進度超過 1 (因最後一幀可能超時)。
  2. 進度達 1 時直接使用 endValue,避免浮點數運算誤差 (如 200.0000001px)。

為什麼間隔設 13ms?

顯示器刷新率通常 60-75Hz → 幀間隔 13-16ms。設 13ms 可盡量對齊螢幕刷新,減少撕裂、提升流暢度。現代瀏覽器提供 requestAnimationFrame (rAF) 自動對齊刷新率。

現代標準:requestAnimationFrame 版本

function animateRAF(element, endValue, duration) {
  var startTime, startValue = parseFloat(getComputedStyle(element).width);
  function step(timestamp) {
    if (!startTime) startTime = timestamp;
    var progress = Math.min(1, (timestamp - startTime) / duration);
    element.style.width = (startValue + (endValue - startValue) * progress) + 'px';
    if (progress < 1) requestAnimationFrame(step);
    else element.innerHTML = timestamp - startTime;
  }
  requestAnimationFrame(step);
}

優勢:

  • 瀏覽器自動決定最佳幀率 (通常 60fps)。
  • 標籤頁隱藏時自動暫停,省電。
  • 時間戳 timestamp 為高精度 DOMHighResTimeStamp (微秒級)。

緩動函式:賦予動畫生命力

// 線性
var linear = t => t;
// 緩入
var easeInQuad = t => t * t;
// 緩出
var easeOutQuad = t => t * (2 - t);
// 緩入緩出
var easeInOutQuad = t => t < 0.5 ? 2*t*t : -1 + (4-2*t)*t;

// 使用
var stepValue = startValue + (endValue - startValue) * easeOutQuad(progress);

CSS Transition/Animation vs JS 動畫

維度CSSJS (rAF)
效能GPU 加速、主執行緒不阻塞主執行緒執行,複雜計算可能掉幀
控制力聲明式、難以動態中斷/回調完全程式化控制、支援複雜邏輯
適用場景簡單狀態切換 (hover、class toggle)遊戲、編輯器、複雜序列、需同步多元素

從累加到時間插值、從 setInterval 到 rAF、從線性到緩動,JavaScript 動畫演進史就是「追求時間精確性與視覺自然度」的歷程。理解底層原理,才能在選擇 CSS 或 JS、引入 GSAP/Anime.js 等庫時做出正確架構決策。

copyright © 萬盛學電腦網 all rights reserved