Aw Qirui Guo Aw Qirui Guo - 2 months ago 6
CSS Question

How to get the coordinates of the point that I click?

I am playing with

<canvas>
tag and just encountered a problem:

https://jsfiddle.net/awguo/6yLqa5hz/

I want to get the coordinates of a point when I click on a canvas.

I searched for a while and found some functions, but as a 300x300 canvas, the point of its right-bottom point is (300,150). Shouldn't it be 300,300 (because the img is 300x300 and the canvas is 100% on it)?

Why?

What should I do to get the
300x300
?

Answer

You must adjust the event.clientX and event.clientY coordinates returned by your event handlers by the offset of the canvas element vs the window. To do that you can use canvas.getBoundingClientRect to get the left & top canvas offsets. Be sure to listen for resize & scroll events. When those events happen you must re-fetch the canvas's current offset.

// Fetch offsetX & offsetY variables that contain the 
// canvas offset versus the window
// Re-fetch when the window is resized or scrolled
function reOffset(){
    var BB=canvas.getBoundingClientRect();
    offsetX=BB.left;
    offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }

Here's how to use the offsets to calculate correct mouse coordinates in an event handler:

function handleMouseDown(e){

    // tell the browser we're handling this event
    e.preventDefault();
    e.stopPropagation();

    // calculate the mouse position
    mouseX=parseInt(e.clientX-offsetX);
    mouseY=parseInt(e.clientY-offsetY);

    // your stuff
}