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

后端 未结 22 2884
忘掉有多难
忘掉有多难 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:58

    See demo at http://jsbin.com/ApuJOSA/1/edit?html,output .

      function mousePositionOnCanvas(e) {
          var el=e.target, c=el;
          var scaleX = c.width/c.offsetWidth || 1;
          var scaleY = c.height/c.offsetHeight || 1;
    
          if (!isNaN(e.offsetX)) 
              return { x:e.offsetX*scaleX, y:e.offsetY*scaleY };
    
          var x=e.pageX, y=e.pageY;
          do {
            x -= el.offsetLeft;
            y -= el.offsetTop;
            el = el.offsetParent;
          } while (el);
          return { x: x*scaleX, y: y*scaleY };
      }
    

提交回复
热议问题