萬盛學電腦網

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

HTML5 Canvas 事件處理機制:從座標偵測到事件代理完整解析

Canvas 內繪製的圖形非 DOM 節點,無法直接綁定事件。本文詳細說明如何透過座標計算與事件代理,實現 Canvas 圖形的點擊、懸停等互動。

核心限制

Canvas 繪圖方法不回傳圖形物件,畫布內部無 DOM 結構:

const ctx = canvas.getContext('2d');
ctx.rect(10, 10, 100, 100);
ctx.stroke();
console.log(ctx.rect(10,10,100,100)); // undefined

點擊畫布上任意位置,觸發的都是 `` 元素的事件。

基本事件代理架構

canvas.addEventListener('click', e => {
  const pos = getEventPosition(e);
  if (ctx.isPointInPath(pos.x, pos.y)) {
    console.log('點擊了矩形');
  }
});

function getEventPosition(ev) {
  if (ev.layerX !== undefined) return {x: ev.layerX, y: ev.layerY};
  // Opera/舊版 Safari 相容
  return {x: ev.offsetX, y: ev.offsetY};
}

isPointInPath() 判斷點擊命中

僅能檢測**目前路徑**,多圖形需重繪檢測:

ctx.rect(10, 10, 100, 100);
ctx.stroke();
ctx.isPointInPath(50, 50); // true

ctx.beginPath();
ctx.rect(110, 110, 100, 100);
ctx.stroke();
ctx.isPointInPath(20, 20); // false(只檢測第二個矩形)

多圖形事件處理:重繪檢測法

  1. 將圖形參數存入陣列
  2. 點擊時清空畫布、逐一重繪並檢測
  3. 收集命中的圖形索引,模擬事件冒泡順序
const shapes = [
  {x:10, y:10, w:100, h:100},
  {x:110, y:110, w:100, h:100}
];

function draw(checkPos) {
  const hits = [];
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  shapes.forEach((s, i) => {
    ctx.beginPath();
    ctx.rect(s.x, s.y, s.w, s.h);
    ctx.stroke();
    if (checkPos && ctx.isPointInPath(checkPos.x, checkPos.y)) {
      hits.push(i); // 記錄命中順序(最後一個為最上層)
    }
  });
  return hits;
}

canvas.addEventListener('click', e => {
  const pos = getEventPosition(e);
  const hitIndices = draw(pos);
  if (hitIndices.length) {
    const topMost = hitIndices[hitIndices.length - 1];
    console.log('點擊圖形:', shapes[topMost]);
  }
});

進階考量

  • 效能:大量圖形時需優化(如離屏 Canvas、空間分割、requestAnimationFrame 節流)。
  • 滑鼠事件:mousemove 高頻觸發,需記錄進出狀態模擬 mouseover/mouseout。
  • 觸控支援:同樣處理 touchstart/touchmove/touchend,座標取自 changedTouches。
  • 現成函式庫:生產環境建議使用 Fabric.js、Konva.js、Two.js 等已處理事件系統的庫。

理解 Canvas 事件代理原理,能讓你在輕量級專案中自行實作互動,或在除錯函式庫時更得心應手。

copyright © 萬盛學電腦網 all rights reserved