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


当前回答

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

这就是我所做的:

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

其他回答

下面计算鼠标位置与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 ;
}

这可以正常工作!

你可以使用相对父类的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)
})

通过事件可以获得画布内的鼠标坐标。offsetX和事件。下面是一个小片段来证明我的观点:

c=document.getElementById("c"); ctx=c.getContext("2d"); ctx.fillStyle="black"; ctx.fillRect(0,0,100,100); c.addEventListener("mousemove",function(mouseEvt){ // the mouse's coordinates on the canvas are just below x=mouseEvt.offsetX; y=mouseEvt.offsetY; // the following lines draw a red square around the mouse to prove it ctx.fillStyle="black"; ctx.fillRect(0,0,100,100); ctx.fillStyle="red"; ctx.fillRect(x-5,y-5,10,10); }); body { background-color: blue; } canvas { position: absolute; top: 50px; left: 100px; } <canvas id="c" width="100" height="100"></canvas>

如果你想获得与一个元素相关的layerX和layerY,也许你可以尝试:

let bbox_rect = document.getElementById("dom-ID").getBoundingClientRect()
let layerX = e.clientX-bbox_rect.left
let layerY = e.clientY-bbox_rect.top