Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  129] [ 1]  / answers: 1 / hits: 18301  / 13 Years ago, fri, june 10, 2011, 12:00:00

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


More From » canvas

 Answers
3

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


jsFiddle.



You should consider attaching events unobtrusively, i.e. not using the onclick HTML attribute.


[#91778] Wednesday, June 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;