码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-27 12:44:51      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

如果给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

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!