JavaScript 動畫看似神奇,背後的原理其實很單純。本文將透過兩個實例,帶你理解動畫的本質,並一步步修正實作中容易忽略的精度與時間問題。
第一版:累加位移
假設需求是把一個 div 的寬度從 100px 變到 200px,最直白的寫法是每隔一段時間就增加 1px:
代碼如下:
<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);
然而動畫結束後顯示的耗時卻往往超過 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);
改良後,動畫耗時的誤差只剩下十幾毫秒。但問題還沒結束:檢查會發現 test2 的最終寬度可能超過 200px。仔細分析可知:
1. percentage 可能大於 1,可用 Math.min 限制最大值。
2. 即使 percentage 不大於 1,只要 endValue 或 startValue 為小數,乘法運算也可能因 JS 浮點精度不足而產生誤差。其實我們只需保證最終值準確,因此在 percentage 為 1 時直接使用 endValue 即可。
於是函式修改為:
代碼如下:
function animate2(element, endValue, duration) {
var startTime = new Date(),
startValue = parseInt(element.style.width);
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);
}
最後還有一個疑問:setInterval 的間隔為何設為 13ms?因為一般顯示器的刷新率不超過 75Hz,也就是大約每 13ms 刷新一次,把間隔與刷新率同步,視覺效果會更順暢。理解了這些細節,你就能寫出既準確又流暢的 JavaScript 動畫。