在没有周围元素存在时跟踪画布中的鼠标位置 [英] Tracking mouse position in canvas when no surrounding element exists

查看:140
本文介绍了在没有周围元素存在时跟踪画布中的鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在获取鼠标位置wrt画布时遇到问题。



有两种情况:



1)如果没有围绕画布div的div元素,那么我可以获得鼠标位置。



包裹在 div ,然后 offsetLeft offsetTop



解决方案

需要一个函数来获取画布元素的位置

  function findPos(obj){
var curleft = 0,curtop = 0;
if(obj.offsetParent){
do {
curleft + = obj.offsetLeft;
curtop + = obj.offsetTop;
} while(obj = obj.offsetParent);
return {x:curleft,y:curtop};
}
return undefined;
}

计算游标相对于当前位置:

  $('#canvas')。mousemove(function(e){
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coordinateDisplay =x =+ x +,y =+ y;
writeCoordinateDisplay(coordinateDisplay);
});

offsetLeft offsetTop 相对于 offsetParent ,这是您的 div 节点。当删除 div 时,它们相对于 body ,因此没有要减去的偏移量。



Similary, e.pageX e.pageY 的光标相对于文档。这就是为什么我们从这些值中减去画布的偏移量,以得到真实的位置。



元素的另一种选择是直接使用值 e.layerX e.layerY 。这比上述方法不可靠,原因有两个:


  1. 这些值也与事件不发生时的整个文档相关



I'm having trouble in getting the mouse position w.r.t canvas.

There are two cases:

1) If there is no div element surrounding the canvas div then I was able to get the mouse position.

2) When the canvas is wrapped in a div then offsetLeft and offsetTop do not work as expected

What accounts for this difference?

解决方案

You need a function to get the position of the canvas element:

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

And calculate the current position of the cursor relative to that:

$('#canvas').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coordinateDisplay = "x=" + x + ", y=" + y;
    writeCoordinateDisplay(coordinateDisplay);
});

The values of offsetLeft and offsetTop are relative to offsetParent, which is your div node. When you remove the div they're relative to the body, so there is no offset to subtract.

Similary, e.pageX and e.pageY give the position of the cursor relative to the document. That's why we subtract the canvas's offset from those values to arrive at the true position.

An alternative for positioned elements is to directly use the values of e.layerX and e.layerY. This is less reliable than the method above for two reasons:

  1. These values are also relative to the entire document when the event does not take place inside a positioned element
  2. They are not part of any standard

这篇关于在没有周围元素存在时跟踪画布中的鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆