JavaScript動畫本質是在時間維度上逐幀修改元素樣式。本文從最基礎的setTimeout遞歸驅動講起,演進到現代requestAnimationFrame、CSS Transition/Animation、Web Animations API,構建完整動畫認知體系。
<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>
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 API | JS控制+原生性能 | 優秀 | 需要暫停/倒播/速度控制的聲明式動畫 |
#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自動暫停,節省資源