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


当前回答

你可以买到它

var element = document.getElementById(canvasId);
element.onmousemove = function(e) {
    var xCoor = e.clientX;
    var yCoor = e.clientY;
}

其他回答

你可以买到它

var element = document.getElementById(canvasId);
element.onmousemove = function(e) {
    var xCoor = e.clientX;
    var yCoor = e.clientY;
}

你可以使用相对父类的getBoudingClientRect()。

document.addEventListener("mousemove", (e) => {
  let xCoord = e.clientX - e.target.getBoundingClientRect().left + e.offsetX
  let yCoord = e.clientY - e.target.getBoundingClientRect().top + e.offsetY
  console.log("xCoord", xCoord, "yCoord", yCoord)
})

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

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

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

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

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

这可以正常工作!