javascript 在javascript中处理画布的OnClick事件并获取其坐标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6300791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:14:33  来源:igfitidea点击:

Handling OnClick event for canvas in javascript and getting its coordinates

javascriptcanvasevent-handlingonclickcoordinates

提问by Ahmad Farid

I have a canvas for drawing like that

我有一个画布可以画那样的

<div id="canvas" style="position:relative;width:600px;height:300px;" onclick="q()"></div>

<div id="canvas" style="position:relative;width:600px;height:300px;" onclick="q()"></div>

I need to handle the event when clicking on it and get the coordinates on the canvas where it was clicked

单击它时我需要处理该事件并获取单击它的画布上的坐标

采纳答案by alex

You need to get the page x and y coordinates, and then minus the canvasoffset to get them relative to the canvas.

您需要获取页面 x 和 y 坐标,然后减去canvas偏移量以获取它们相对于canvas.

function q(event) {
    event = event || window.event;

    var canvas = document.getElementById('canvas'),
        x = event.pageX - canvas.offsetLeft,
        y = event.pageY - canvas.offsetTop;

    alert(x + ' ' + y);
}

jsFiddle.

js小提琴

You should consider attaching events unobtrusively, i.e. notusing the onclickHTML attribute.

您应该考虑不显眼地附加事件,即使用onclickHTML 属性。

回答by Jeremy

Using jQuery, you can just read the .pageX and .pageY attributes directly.

使用 jQuery,您可以直接读取 .pageX 和 .pageY 属性。

http://docs.jquery.com/Tutorials:Mouse_Position#Where_did_they_click_that_div.3F

http://docs.jquery.com/Tutorials:Mouse_Position#Where_did_they_click_that_div.3F

回答by Edward Dixon

Since HTML5, just get the layerX and layerY attributes of the event itself. Nice!

从 HTML5 开始,只需要获取事件本身的 layerX 和 layerY 属性。好的!