How do I get the coordinates of a mouse click on a canvas element?

后端 未结 22 2812
忘掉有多难
忘掉有多难 2020-11-21 23:56

What\'s the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

No

22条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 00:34

    Edit 2018: This answer is pretty old and it uses checks for old browsers that are not necessary anymore, as the clientX and clientY properties work in all current browsers. You might want to check out Patriques Answer for a simpler, more recent solution.

    Original Answer:
    As described in an article i found back then but exists no longer:

    var x;
    var y;
    if (e.pageX || e.pageY) { 
      x = e.pageX;
      y = e.pageY;
    }
    else { 
      x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
      y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
    } 
    x -= gCanvasElement.offsetLeft;
    y -= gCanvasElement.offsetTop;
    

    Worked perfectly fine for me.

提交回复
热议问题