I have a canvas for drawing like that
<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
I have a canvas for drawing like that
<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
Share Improve this question asked Jun 10, 2011 at 0:32 Ahmad FaridAhmad Farid 14.8k45 gold badges98 silver badges138 bronze badges3 Answers
Reset to default 10You need to get the page x and y coordinates, and then minus the canvas
offset to get them relative to the 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.
You should consider attaching events unobtrusively, i.e. not using the onclick
HTML attribute.
Using jQuery, you can just read the .pageX and .pageY attributes directly.
http://docs.jquery.com/Tutorials:Mouse_Position#Where_did_they_click_that_div.3F
Since HTML5, just get the layerX and layerY attributes of the event itself. Nice!