萬盛學電腦網

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

JavaScript動畫實現原理:setTimeout/ requestAnimationFrame 驅動的移動效果

JavaScript動畫本質是在時間維度上逐幀修改元素樣式。本文從最基礎的setTimeout遞歸驅動講起,演進到現代requestAnimationFrame、CSS Transition/Animation、Web Animations API,構建完整動畫認知體系。

基礎版:setTimeout 遞歸驅動 (原文示例)

<div id="div1" style="position:absolute; left:10px; top:10px; background:#FFFFCC; padding:10px;">I can moving...</div>
<button onclick="startMove()">開始移動</button>
<button onclick="stopMove()">停止移動</button>

<script>
var movingID = null;
var div1 = document.getElementById('div1');

function startMove() {
    var left = parseInt(div1.style.left) || 0;
    if (left < document.body.clientWidth - 150) {
        div1.style.left = (left + 1) + 'px';
    } else {
        div1.style.left = '10px'; // 歸位
    }
    movingID = setTimeout(startMove, 10); // ~100fps
}

function stopMove() {
    clearTimeout(movingID);
}
</script>

進階版:requestAnimationFrame (現代標準)

var animationId = null;
var startTime = null;
var duration = 2000; // 2秒
var startX = 10;
var endX = 500;

function animate(timestamp) {
    if (!startTime) startTime = timestamp;
    var progress = Math.min((timestamp - startTime) / duration, 1);
    
    // 緩動函數
    var eased = easeOutCubic(progress);
    div1.style.left = (startX + (endX - startX) * eased) + 'px';
    
    if (progress < 1) {
        animationId = requestAnimationFrame(animate);
    }
}

function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }

function startRAF() { startTime = null; animationId = requestAnimationFrame(animate); }
function stopRAF() { cancelAnimationFrame(animationId); }

三種動畫方案對比

方案控制力性能適用場景
JS setTimeout/setInterval完全控制、邏輯複雜較差、不對齊刷新率舊瀏覽器兼容、極簡邏輯
JS requestAnimationFrame完全控制、對齊刷新率(60fps)優秀、瀏覽器優化複雜軌跡、物理模擬、Canvas/WebGL
CSS Transition/Animation聲明式、GPU加速最優、合成器線程狀態切換、hover、載入動畫
Web Animations APIJS控制+原生性能優秀需要暫停/倒播/速度控制的聲明式動畫

CSS 實現同樣效果 (推薦)

#div1 {
    position: absolute;
    left: 10px;
    top: 10px;
    transition: left 2s cubic-bezier(0.215, 0.61, 0.355, 1); /* easeOutCubic */
}
#div1.moving { left: 500px; }

// JS 只需切換類
div1.classList.add('moving'); // 開始
div1.classList.remove('moving'); // 歸位 (需配合 transitionend)

關鍵知識點總結

  • setTimeout(fn, 10) ≠ 100fps,實際受事件循環、主線程阻塞影響
  • requestAnimationFrame回調參數timestamp為高精度時間戳,用於計算幀進度
  • 動畫中只讀寫合成屬性:transform, opacity (GPU加速),避免left/top/width/height觸發佈局重排
  • will-change: transform提前提示瀏覽器優化
  • 頁面不可見時requestAnimationFrame自動暫停,節省資源

物理動畫庫推薦

  • GSAP:專業級、時間線、插件生態豐富
  • Motion One:輕量、WAAPI封裝、現代語法
  • Framer Motion:React首選、聲明式、手勢支援
  • Anime.js:輕量、時間線、SVG/Canvas/DOM通用
copyright © 萬盛學電腦網 all rights reserved