利用 drawImage() 九參數版本,從精靈圖切割單幀並按時間間隔繪製,構建流暢幀動畫。核心:setTimeout/requestAnimationFrame 驅動幀索引遞增與重繪。
ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) — 前四參數切割源區域,後四參數繪製目標區域col = frame % cols; row = Math.floor(frame / cols)setTimeout(update, 1000/fps) 或 requestAnimationFrame 配合時間戳控制幀率<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas 幀動畫 Demo</title>
<style>canvas { background: #000; display: block; margin: 20px auto; }</style>
</head>
<body>
<canvas id="animCanvas" width="600" height="400"></canvas>
<script>
const canvas = document.getElementById('animCanvas');
const ctx = canvas.getContext('2d');
const FRAMES = 22; // 總幀數
const COLS = 5; // 精靈圖列數
let frame = 0;
let img = new Image();
img.src = 'robin.png'; // 5x5 網格精靈圖
img.onload = () => {
const fw = img.naturalWidth / COLS;
const fh = img.naturalHeight / Math.ceil(FRAMES/COLS);
let px = 300, py = 300; // 第一隻雁位置
let x2 = 300, y2 = 0; // 第二隻雁位置
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 計算當前幀在精靈圖中的位置
const col = frame % COLS;
const row = Math.floor(frame / COLS);
const sx = col * fw;
const sy = row * fh;
// 雁 A:左上移動
px -= 2; py -= 2;
if (px < -fw) px = canvas.width;
if (py < -fh) py = canvas.height;
ctx.drawImage(img, sx, sy, fw, fh, px, py, fw, fh);
// 雁 B:左下移動
x2 -= 2; y2 += 2;
if (x2 < -fw) { x2 = canvas.width; y2 = 0; }
ctx.drawImage(img, sx, sy, fw, fh, x2, y2, fw, fh);
frame = (frame + 1) % FRAMES;
requestAnimationFrame(update);
}
update();
};
</script>
</body>
</html>

requestAnimationFrame 替代 setTimeout,瀏覽器自動對齊刷新率{sx, sy} 存入陣列,避免每幀重複運算{frame, x, y, speed}精靈圖幀動畫是 2D 遊戲、互動插圖、Loading 動畫的基石技術,掌握切割與時序控制即可釋放無限創意。