我想做一个小绘画应用程序使用画布。所以我需要找到鼠标在画布上的位置。


当前回答

使用此方法快速获取鼠标位置:

Object.defineProperty(MouseEvent.prototype, "mouseX", {
   get() {
      return this.clientX - this.currentTarget.getBoundingClientRect().left;
   }
});
Object.defineProperty(MouseEvent.prototype, "mouseY", {
   get() {
      return this.clientY - this.currentTarget.getBoundingClientRect().top;
   }
});

例子:

document.body.onmousemove=function(e){console.log(e.mouseX,e.mouseY)}

其他回答

下面计算鼠标位置与canvas元素的关系:

const example = document.getElementById('example');

example.onmousemove = function(e) { 
    const x = e.pageX - e.currentTarget.offsetLeft; 
    const y = e.pageY - e.currentTarget.offsetTop; 
}

关于这个问题的难点可以在这里找到:http://www.quirksmode.org/js/events_properties.html#position

使用这里描述的技术,您可以在文档中找到鼠标的位置。然后你只需检查它是否在元素的边界框内,你可以通过调用element. getboundingclientrect()来找到它,它将返回一个具有以下属性的对象:{bottom, height, left, right, top, width}。由此,判断偶数是否发生在元素内部是很简单的。

function myFunction(e) {
    var x =  e.clientX - e.currentTarget.offsetLeft ; 
    var y = e.clientY - e.currentTarget.offsetTop ;
}

这可以正常工作!

因为我没有找到一个解决方案,可以帮助你得到它,如果你把它附加到一个父母元素,你有一个例如选择。

这就是我所做的:

let positions = {
  x: event.pageX,
  y: event.pageY - event.currentTarget.getBoundingClientRect().top + event.currentTarget.offsetTop
}

这是我得到的。

    $(".some-class").click(function(e) {

    var posx = 0;
    var posy = 0;

    posx = e.pageX;
    posy = e.pageY;

    alert(posx);
    alert(posy);
});