How do I get the coordinates of a mouse click on a canvas element?

后端 未结 22 2755
忘掉有多难
忘掉有多难 2020-11-21 23:56

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

No

22条回答
  •  庸人自扰
    2020-11-22 00:59

    Modern browser's now handle this for you. Chrome, IE9, and Firefox support the offsetX/Y like this, passing in the event from the click handler.

    function getRelativeCoords(event) {
        return { x: event.offsetX, y: event.offsetY };
    }
    

    Most modern browsers also support layerX/Y, however Chrome and IE use layerX/Y for the absolute offset of the click on the page including margin, padding, etc. In Firefox, layerX/Y and offsetX/Y are equivalent, but offset didn't previously exist. So, for compatibility with slightly older browsers, you can use:

    function getRelativeCoords(event) {
        return { x: event.offsetX || event.layerX, y: event.offsetY || event.layerY };
    }
    

提交回复
热议问题