Handling OnClick event for canvas in javascript and getting its coordinates

Ahmad Farid picture Ahmad Farid · Jun 10, 2011 · Viewed 17.9k times · Source

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

Answer

alex picture alex · Jun 10, 2011

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.