預先定義每一幀元素的「動作指令」(創建、移動、顯示、隱藏),定時器按序執行指令,實現類似 Flash 逐幀動畫的效果。適用於軌跡複雜、非線性動畫。
class FrameAnimator {
/**
* @param {string} containerId - 容器元素 ID
* @param {string} idPrefix - 動態元素 ID 前綴
* @param {number} startId - 起始 ID
*/
constructor(containerId, idPrefix = 'anim_', startId = 1) {
this.container = document.getElementById(containerId);
if (!this.container) throw new Error('Container not found');
this.idPrefix = idPrefix;
this.nextId = startId;
this.commands = []; // 主命令隊列
this.backupCommands = []; // 循環備份
this.running = false;
this.timer = null;
this.interval = 50; // 幀間隔(ms)
}
/**
* 添加命令到隊列尾部(反向 unshift 實現先進先出)
* @param {string} cmd - 命令字符串,格式: "id,action,param1,param2"
* action: a=創建, m=移動, s=顯示, h=隱藏
*/
addCommand(cmd) {
this.commands.unshift(cmd);
return this;
}
/** 備份當前命令隊列,用於循環播放 */
backup() {
this.backupCommands = [...this.commands];
return this;
}
/** 設置幀間隔 */
setInterval(ms) {
this.interval = ms;
return this;
}
/** 啟動動畫 */
start() {
if (this.running) return this;
this.running = true;
this._tick();
return this;
}
/** 停止動畫 */
stop() {
this.running = false;
if (this.timer) clearTimeout(this.timer);
this.timer = null;
return this;
}
/** 重置並重新開始 */
restart() {
this.commands = [...this.backupCommands];
this.nextId = this.backupCommands.length ?
Math.max(...this.backupCommands.map(c => parseInt(c.split(',')[0]))) + 1 : 1;
return this.start();
}
_tick() {
if (!this.running || this.commands.length === 0) {
// 循環播放:從備份恢復
if (this.backupCommands.length) {
this.commands = [...this.backupCommands];
this._tick();
}
return;
}
const cmdStr = this.commands.pop();
const cmds = cmdStr.split(';'); // 一幀可包含多條指令
for (const cmd of cmds) {
if (!cmd) continue;
const [idStr, action, p1, p2] = cmd.split(',');
const id = parseInt(idStr);
this._execute(id, action, p1, p2);
}
this.timer = setTimeout(() => this._tick(), this.interval);
}
_execute(id, action, p1, p2) {
const elId = this.idPrefix + id;
let el = document.getElementById(elId);
switch (action) {
case 'a': // add - 創建新元素
if (!el) {
el = document.createElement('a'); // 或 div/span
el.className = 'anim-element';
el.id = elId;
el.style.position = 'absolute';
this.container.appendChild(el);
}
// 穿透到 move
case 'm': // move
if (el) {
el.style.left = parseInt(p1) + 'px';
el.style.top = parseInt(p2) + 'px';
}
break;
case 's': // show
if (el) el.style.display = 'block';
break;
case 'h': // hide
if (el) el.style.display = 'none';
break;
}
}
/** 靜態工廠 */
static create(containerId, idPrefix, startId) {
return new FrameAnimator(containerId, idPrefix, startId);
}
}
// 導出
if (typeof module !== 'undefined') module.exports = FrameAnimator;
else window.FrameAnimator = FrameAnimator;
.anim-element {
position: absolute;
width: 8px;
height: 8px;
background: #ccc;
border-radius: 50%;
pointer-events: none; /* 避免阻擋交互 */
will-change: transform, opacity; /* 渲染優化提示 */
}
const animator = FrameAnimator.create('stage', 'dot_', 1)
.setInterval(50); // 20fps
// 預定義軌跡點 (x, y)
const path = [
[10, 10], [20, 10], [30, 10], [40, 10], [50, 10], // →
[50, 20], [50, 30], [50, 40], [50, 50], // ↓
[40, 50], [30, 50], [20, 50], [10, 50], // ←
[10, 60], [10, 70], [10, 80], [10, 90], // ↓
[20, 90], [30, 90], [40, 90], [50, 90] // →
];
// 生成命令:每點創建一個元素並定位
path.forEach(([x, y], i) => {
animator.addCommand(`${i+1},a,${x},${y}`);
});
// 循環播放
animator.backup().start();
// 交互控制
document.getElementById('pause').onclick = () => animator.stop();
document.getElementById('resume').onclick = () => animator.start();
document.getElementById('restart').onclick = () => animator.restart();
// 同一幀操作多個元素(用 ; 分隔)
animator.addCommand('1,m,100,100;2,m,200,100;3,m,150,200');
// 動態創建粒子效果
function createParticleBurst(animator, centerX, centerY, count = 20) {
for (let i = 0; i < count; i++) {
const angle = (Math.PI * 2 * i) / count;
const radius = 50 + Math.random() * 50;
const x = centerX + Math.cos(angle) * radius;
const y = centerY + Math.sin(angle) * radius;
const id = animator.nextId++;
// 創建 -> 移動 -> 延遲隱藏
animator.addCommand(`${id},a,${centerX},${centerY}`);
animator.addCommand(`${id},m,${x},${y}`);
// 這裡需擴展支持延遲命令,或用 setTimeout 回調中調用 hide
}
}
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| Canvas 逐幀繪製 | 性能極佳、無 DOM 開銷、支持濾鏡/混合模式 | 需手繪邏輯、無 DOM 事件、無障礙難 | 遊戲、粒子特效、數據可視化 |
| CSS Animation/Keyframes | GPU 加速、聲明式、無 JS 運行時 | 動態路徑難控制、調試困難 | 固定路徑 UI 動畫 |
| Web Animations API | 原生、可控、支持時間線 | IE 不支持、Safari 曾有 Bug | 現代項目複雜動畫 |
| GSAP | 功能最強、時間線、插件豐富、性能好 | 體積 ~50KB、商業項目需授權 | 專業動畫需求 |
| FrameAnimator (本文) | 邏輯簡單、DOM 直觀、零依賴、易調試 | DOM 節點多時性能差、非 GPU 加速 | 輕量級、路徑固定、教學演示 |
el.style.transform = `translate(${x}px, ${y}px)` 觸發合成器層,不觸發佈局重排will-change: transform 或 translateZ(0)
_execute(id, action, p1, p2) {
const elId = this.idPrefix + id;
let el = document.getElementById(elId);
switch (action) {
case 'a':
if (!el) {
el = document.createElement('div');
el.className = 'anim-element';
el.id = elId;
this.container.appendChild(el);
}
case 'm':
if (el) {
// 使用 transform 不觸發重排
el.style.transform = `translate(${parseInt(p1)}px, ${parseInt(p2)}px)`;
el.style.display = 'block';
}
break;
case 'h':
if (el) el.style.display = 'none';
break;
}
}