動畫的本質是「隨時間改變某個數值」。多數人第一版會寫成每個 interval 加一點,但這樣做會有兩個問題:耗時不準、終值不準。本文用一個把 div 寬度從 100px 推到 200px 的簡單需求,示範如何逐步修正。
<div id="test1" style="width:100px; height:100px; background:blue; color:white;"></div>
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);
邏輯是每隔一段時間加 1px,加到 200 為止。但執行完會發現實際耗時遠多於 1 秒,通常要 1.5 秒左右。原因很單純:setInterval 並不能嚴格保證執行間隔,主執行緒忙碌時它就會延後,誤差就這樣一格格累積起來。
小學數學題:A 樓與 B 樓相距 100 公尺,我以等速走了 5 分鐘抵達,請問第 3 分鐘時距離 A 樓多遠?答案是 100 × 3 ÷ 5 = 60 公尺。
啟發在於:任一時刻的位置都能用公式直接算出來,不必從起點一格一格加。動畫同理,只要知道「已過時間 ÷ 總時間」這個百分比,就能算出目前該顯示的值:
<div id="test2" style="width:100px; height:100px; background:red; color:white;"></div>
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);
}
animate2(document.getElementById('test2'), 200, 1000);
改完之後誤差降到十幾毫秒等級。但還有小尾巴:檢查元素會發現最終寬度可能不是剛好 200px。
percentage 可能大於 1,導致衝過頭,用 Math.min 夾住最大值即可;(endValue - startValue) * percentage 仍會因 JavaScript 浮點精度而產生誤差。真正需要保證的其實只有「最後一幀等於終值」,所以在 percentage 為 1 時直接指定 endValue 就好。var timerId = setInterval(function() {
// 保證百分率不大於 1
var percentage = Math.min(1, (new Date - startTime) / duration);
var stepValue;
if (percentage >= 1) {
stepValue = endValue; // 保證最終值精準
} else {
stepValue = startValue + (endValue - startValue) * percentage;
}
element.style.width = stepValue + 'px';
if (percentage >= 1) {
clearInterval(timerId);
element.innerHTML = new Date - startTime;
}
}, 13);
傳統顯示器刷新率多在 60~75Hz 之間,75Hz 相當於每 13 毫秒刷新一次。把計時器間隔對齊刷新節奏,畫面看起來會更順。今天的做法是直接用 requestAnimationFrame,由瀏覽器決定最佳時機,比自行猜一個數字更準也更省電。
把這套思路記牢:用時間比例推算數值、明確保證終值、把更新頻率對齊畫面刷新,就掌握了寫動畫的骨架,後面的 easing 函式也只是在這個框架上換算方式而已。