如果给Canvas添加 onmousedown事件,获取到的鼠标位置都是相对于当前文档的位置(x,y):

        获取鼠标点击相对于Canva位置的2种方法      

第一种转换:

         (x-x1,y-y1)

 

      x,y为鼠标点击位置,getBoundingClientRect方法是canvas自带的获取可绘画区域的位置信息的函数

function windowToCanvas(x, y) {
   var bbox = canvas.getBoundingClientRect();
   return { x: x - bbox.left * (canvas.width  / bbox.width),
            y: y - bbox.top  * (canvas.height / bbox.height) };
}

 

第二种更加简洁:

    

canvas.onmousedown = function (e) {
   //var loc = windowToCanvas(e.clientX||e.x, e.clientY||e.y);
   var x=e.layerX||e.offsetX;
   var y=e.layerY||e.offsetY;
   e.preventDefault(); // prevent cursor change

   saveDrawingSurface();
   mousedown.x = loc.x;
   mousedown.y = loc.y;
   dragging = true;
};

     只有firefox支持layerX,其他浏览器支持标准的offsetX

相关文章:

  • 2022-12-23
  • 2021-05-22
  • 2021-07-14
  • 2021-11-02
  • 2021-09-24
  • 2021-07-03
  • 2021-06-03
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-30
  • 2022-12-23
  • 2021-05-14
  • 2021-11-29
相关资源
相似解决方案