萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Canvas 幀動畫實現:精靈圖逐幀播放核心技法

利用 drawImage() 九參數版本,從精靈圖切割單幀並按時間間隔繪製,構建流暢幀動畫。核心:setTimeout/requestAnimationFrame 驅動幀索引遞增與重繪。

關鍵技術點

  • 精靈圖:單張圖片包含所有動畫幀,網格排列(如 5×5 = 25 幀)
  • 幀切割: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>

大雁飛行動畫效果 精靈圖源文件 (5x5 網格)

進階優化建議

  1. 使用 requestAnimationFrame 替代 setTimeout,瀏覽器自動對齊刷新率
  2. 預計算所有幀的 {sx, sy} 存入陣列,避免每幀重複運算
  3. 多角色動畫:維護獨立狀態對象 {frame, x, y, speed}
  4. 動畫狀態機:待機/跑/跳 狀態切換對應不同精靈圖區域
  5. 離屏 Canvas 預渲染複雜角色,主畫布僅繪製合成

精靈圖幀動畫是 2D 遊戲、互動插圖、Loading 動畫的基石技術,掌握切割與時序控制即可釋放無限創意。

copyright © 萬盛學電腦網 all rights reserved