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


当前回答

因为我没有找到一个jquery免费的答案,我可以复制/粘贴,这里是我使用的解决方案:

document.getElementById('clickme').onclick = function(e) { // e = Mouse click event. var rect = e.target.getBoundingClientRect(); var x = e.clientX - rect.left; //x position within the element. var y = e.clientY - rect.top; //y position within the element. console.log("Left? : " + x + " ; Top? : " + y + "."); } #clickme { margin-top: 20px; margin-left: 100px; border: 1px solid black; cursor: pointer; } <div id="clickme">Click Me -<br> (this box has margin-left: 100px; margin-top: 20px;)</div>

完整的例子

其他回答

通过事件可以获得画布内的鼠标坐标。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>

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

这可以正常工作!


const findMousePositionRelativeToElement = (e) => {
    const xClick = e.clientX - e.currentTarget.offsetLeft;
    const yClick = e.clientY - e.currentTarget.offsetTop;
    console.log(`x: ${xClick}`);
    console.log(`y: ${yClick}`);

    // or
    const rect = e.currentTarget.getBoundingClientRect();
    const xClick2 = e.clientX - rect.left;
    const yClick2 = e.clientY - rect.top;
    console.log(`x2: ${xClick2}`);
    console.log(`y2: ${yClick2}`);
}

基于@Spider的解决方案,我的非JQuery版本是这样的:

// Get the container element's bounding box
var sides = document.getElementById("container").getBoundingClientRect();

// Apply the mouse event listener
document.getElementById("canvas").onmousemove = (e) => {
  // Here 'self' is simply the current window's context
  var x = (e.clientX - sides.left) + self.pageXOffset;
  var y = (e.clientY - sides.top) + self.pageYOffset;
}

这适用于滚动和缩放(在这种情况下,有时它返回浮动)。

因为我没有找到一个jquery免费的答案,我可以复制/粘贴,这里是我使用的解决方案:

document.getElementById('clickme').onclick = function(e) { // e = Mouse click event. var rect = e.target.getBoundingClientRect(); var x = e.clientX - rect.left; //x position within the element. var y = e.clientY - rect.top; //y position within the element. console.log("Left? : " + x + " ; Top? : " + y + "."); } #clickme { margin-top: 20px; margin-left: 100px; border: 1px solid black; cursor: pointer; } <div id="clickme">Click Me -<br> (this box has margin-left: 100px; margin-top: 20px;)</div>

完整的例子