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};
}
僅能檢測**目前路徑**,多圖形需重繪檢測:
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(只檢測第二個矩形)
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]);
}
});
mousemove 高頻觸發,需記錄進出狀態模擬 mouseover/mouseout。touchstart/touchmove/touchend,座標取自 changedTouches。理解 Canvas 事件代理原理,能讓你在輕量級專案中自行實作互動,或在除錯函式庫時更得心應手。