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
You 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);
}
You should consider attaching events unobtrusively, i.e. not using the onclick
HTML attribute.