利用 HTML5 <canvas> 的 drawImage() 方法,配合精靈圖,即可實作流暢的角色走路動畫。本文詳細拆解三種繪圖模式與動畫邏輯。
drawImage(image, x, y) — 將完整圖像繪製至指定座標。drawImage(image, x, y, width, height) — 依指定寬高縮放後繪製。drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) — 從來源圖像裁切特定區域,再縮放至目標區域。此為動畫幀切換的核心。取得超級瑪麗連續走路動作的精靈圖(每幀寬高固定),例如:

<canvas id="gameCanvas" width="800" height="400">瀏覽器不支援 Canvas</canvas>
<button id="btnStart">開始動畫</button>
<button id="btnStop">暫停動畫</button>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const marioImg = new Image();
marioImg.src = 'mario_sprite.png'; // 精靈圖路徑
const frameWidth = 32, frameHeight = 48; // 單幀尺寸
let currentFrame = 0, totalFrames = 3;
let posX = 50, posY = 300;
let animationId, isRunning = false;
function animate() {
if (!isRunning) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 使用第三種 drawImage 裁切當前幀
ctx.drawImage(marioImg,
currentFrame * frameWidth, 0, frameWidth, frameHeight, // 來源區域
posX, posY, frameWidth * 2, frameHeight * 2); // 目標區域(放大 2 倍)
currentFrame = (currentFrame + 1) % totalFrames;
posX += 5; // 向右移動
if (posX > canvas.width) posX = -frameWidth * 2; // 循環
animationId = requestAnimationFrame(animate);
}
document.getElementById('btnStart').onclick = () => { isRunning = true; animate(); };
document.getElementById('btnStop').onclick = () => { isRunning = false; cancelAnimationFrame(animationId); };
requestAnimationFrame 替代 setInterval,效能更佳。