Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling OnClick event for canvas in javascript and getting its coordinates

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

like image 915
Ahmad Farid Avatar asked Jun 10 '11 00:06

Ahmad Farid


People also ask

How do I find coordinates in canvas?

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.

Does canvas support event handlers?

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.

How do you use the click method in JavaScript?

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.


1 Answers

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.

like image 140
alex Avatar answered Sep 27 '22 21:09

alex