簡體   English   中英

如何使 canvas 個元素可點擊

[英]How to make canvas elements clickable

我正在嘗試制作 MineSweeper 游戲,並且到目前為止已經制作了我需要的所有單元格,但我還需要單元格可點擊以移除它們的封面,但似乎沒有辦法做到這一點。

我已經將每個 object 推入一個數組並嘗試循環遍歷它然后添加 EventListener 但它說 cell.addEventListener 不是 function 如果我嘗試在單元格數組上添加 onclick 函數。 我做錯了什么還是不可能做到?

 const canvas = document.getElementById("myCanvas") const ctx = canvas.getContext("2d") canvas.style.border = "1px solid black" class Cell { constructor(x, y, w) { this.x = x this.y = y this.w = w let bomb = false let revealed = false } show() { ctx.beginPath() ctx.rect(this.x, this.y, this.w, this.w) ctx.stroke() } } let w = canvas.width let h = canvas.height let ColumnRow = w / 15 let cell = [] function setup() { for (let x = 0; x < w - 1; x += ColumnRow) { for (let y = 0; y < h - 1; y += ColumnRow) { cell.push(new Cell(x, y, ColumnRow)) } } } function draw() { for (let c of cell) { c.show() } } function update() { setup() draw() requestAnimationFrame(update) } update()
 <canvas id="myCanvas" width="500" height="500"></canvas>

您應該使用Path2D構造函數來檢查點擊事件是否在特定的 canvas 路徑內:

 const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); canvas.style.border = '1px solid black'; class Cell { constructor(x, y, w) { this.x = x; this.y = y; this.w = w; let bomb = false; let revealed = false; } create() { // Create cell const cell = new Path2D(); cell.rect(this.x, this.y, this.w, this.w); ctx.stroke(cell); this.cell = cell; } } const w = canvas.width; const h = canvas.height; const ColumnRow = w / 15; const cells = []; function setup() { for (let x = 0; x < w - 1; x += ColumnRow) { for (let y = 0; y < h - 1; y += ColumnRow) { cells.push(new Cell(x, y, ColumnRow)); } } } function draw() { for (const cell of cells) { cell.create(); } } function addListeners() { const handler = function (event) { for (const cell of cells) { if (ctx.isPointInPath(cell.cell, event.offsetX, event.offsetY)) { ctx.strokeStyle = 'green'; ctx.fillStyle = 'green'; ctx.fill(cell.cell); } else { ctx.clearRect(cell.x, cell.y, cell.w, cell.w); ctx.strokeStyle = 'red'; } } }; canvas.addEventListener('click', handler); } function update() { setup(); draw(); requestAnimationFrame(update); } update(); addListeners();
 <canvas id="myCanvas"></canvas>

某區canvas:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM