製作循環動畫(如角色行走、跑步、跳舞)時,開發者常面臨:動作停留幀數、過渡幀數如何分配才能在 100% 內剛好閉合?靠試錯調參數極其低效、心力交瘁。

線段圖示:
0% x% x+y% 2x+y% ... 100%
├─動作1─┤┌過渡y┐├─動作2─┤┌過渡y┐├─動作3─┤ ...
規律:n 個動作 = n 個停留段 + (n-1) 個過渡段
方程:n·x + (n-1)·y = 100
3x + 2y = 100
/* 嘗試 x=20 → y=20 → 完美整除 */
@keyframes walk {
0%, 20% { /* 動作1 */ }
40%, 60% { /* 動作2 */ }
80%, 100% { /* 動作3 */ }
}
animation-direction: alternate 會在反向播放時重複首尾動作的停留段,導致節奏破碎。

修正方程:(n-1)·x + (n-1)·y = 100 → (n-1)(x + y) = 100
(3-1)(x+y) = 100 → x+y = 50
/* 取 x=20, y=30 */
@keyframes walk {
0%, 20% { /* 動作1 - 僅開頭停留 */ }
50%, 70% { /* 動作2 - 完整停留+過渡 */ }
100% { /* 動作3 - 僅結尾停留,無過渡 */ }
}
/* 反向播放時:動作3→動作2→動作1,節奏完美對稱 */
/* JavaScript 版計算器 */
function generateKeyframes(n, x, y, bidirectional = false) {
const frames = [];
let pos = 0;
if (bidirectional) {
// 雙向:首尾各一個停留段,中間 n-2 個完整段
frames.push({start: 0, end: x, action: 1}); // 動作1 停留
for (let i = 2; i < n; i++) {
pos = (i-1)*(x+y);
frames.push({start: pos, end: pos+x, action: i}); // 中間動作
pos += x;
frames.push({start: pos, end: pos+y, action: 'trans'}); // 過渡
}
frames.push({start: 100-x, end: 100, action: n}); // 動作n 停留
} else {
// 單向:n 個完整段
for (let i = 1; i <= n; i++) {
pos = (i-1)*(x+y);
frames.push({start: pos, end: pos+x, action: i});
if (i < n) frames.push({start: pos+x, end: pos+x+y, action: 'trans'});
}
}
return frames;
}
// 使用
console.log(generateKeyframes(3, 20, 20, false)); // 單向
console.log(generateKeyframes(3, 20, 30, true)); // 雙向
/* 8 幂跑步動畫,單向循環 */
@keyframes run {
0% { background-position: 0 0; }
12.5% { background-position: -180px 0; }
25% { background-position: -360px 0; }
37.5% { background-position: -540px 0; }
50% { background-position: -720px 0; }
62.5% { background-position: -900px 0; }
75% { background-position: -1080px 0; }
87.5% { background-position: -1260px 0; }
100% { background-position: 0 0; } /* 閉合回第一幂 */
}
/* 等距分佈公式:100% / 幂數 = 12.5% */
.sprite-run {
width: 180px; height: 240px;
background: url(sprite-run.png) 0 0 no-repeat;
animation: run 0.8s steps(8) infinite; /* steps() 逐幂播放,更流暢 */
}
| 模式 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
| steps(n) | 精靈圖、像素藝術、固定幂數 | 性能極佳、無插值模糊、精確控制 | 無法平滑過渡 |
| 關鍵幂插值 | 位移、旋轉、縮放、顏色漸變 | 平滑自然、瀏覽器自動插值 | 需手動計算百分比 |
掌握 n·x + (n-1)·y = 100(單向)與 (n-1)(x+y) = 100(雙向)兩大核心公式,配合 steps() 逐幂動畫,即可科學、高效地製作任何循環動畫。建議將計算器封裝為團隊共用 Snippet 或 VS Code 插件,徹底告別「靠感覺調參數」的低效時代。