本文介绍了如何获取鼠标在画布元素上单击的坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将单击事件处理程序添加到将返回单击的 x 和 y 坐标(相对于画布元素)的画布元素的最简单方法是什么?

What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

不需要兼容旧版浏览器,Safari、Opera 和 Firefox 都可以.

No legacy browser compatibility required, Safari, Opera and Firefox will do.

推荐答案

如果您喜欢简单但仍需要跨浏览器功能,我发现此解决方案最适合我.这是@Aldekein 解决方案的简化,但没有 jQuery.

If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but without jQuery.

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)
})

这篇关于如何获取鼠标在画布元素上单击的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 01:43