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

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

              

第一种转换:

         (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

原文地址:https://www.cnblogs.com/liuminghai/p/4459714.html