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
The coordinates of the mouse whenever a click takes place can be found by detecting the click event with an event listener and finding the event's x and y position. A function is created which takes in the canvas element and event as parameters.
The Canvas event handling system closely follows the W3C DOM Event Model. If you have already used events in JavaScript and HTML most concepts of the Canvas event system should be already familiar to you. The most notable difference is the missing capture phase, but it is usually not used anyhow.
Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With