取得畫布元素上的滑鼠點選座標
要取得滑鼠點選相對於畫布元素的 x 和 y座標,請執行以下操作這些步驟:
定義事件處理程序:
canvas.addEventListener('mousedown', function(e) { // Code to get cursor position })
const rect = canvas.getBoundingClientRect() const x = event.clientX - rect.left const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
function getCursorPosition(canvas, event) { const rect = canvas.getBoundingClientRect() const x = event.clientX - rect.left const y = event.clientY - rect.top console.log("x: " + x + " y: " + y) } const canvas = document.querySelector('canvas') canvas.addEventListener('mousedown', function(e) { getCursorPosition(canvas, e) })
以上是如何取得 Canvas 元素上的滑鼠點擊座標?的詳細內容。更多資訊請關注PHP中文網其他相關文章!