Aw Qirui Guo Aw Qirui Guo - 10 months ago 42
CSS Question

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

I am playing with

tag and just encountered a problem:

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)?


What should I do to get the

Answer Source

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();
var offsetX,offsetY;
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

    // calculate the mouse position

    // your stuff