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


当前回答

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

其他回答

Mark van Wyk的回答让我找到了正确的方向,但并没有完全解决我的问题。我仍然在另一个元素中包含的元素中绘画。

以下解决了它为我:

        x = e.pageX - this.offsetLeft - $(elem).offset().left;
        y = e.pageY - this.offsetTop - $(elem).offset().top;

换句话说,我简单地堆叠了所有嵌套元素的偏移量

这是我得到的。

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

    var posx = 0;
    var posy = 0;

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

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

我尝试了所有这些解决方案,由于我的特殊设置与矩阵转换容器(panzoom库)没有工作。这将返回正确的值,即使缩放和窗格:

mouseevent(e) {
 const x = e.offsetX,
       y = e.offsetY
}

但前提是没有子元素。这可以通过使用CSS使它们对事件“不可见”来规避:

.child {
   pointer-events: none;
}

因为我没有找到一个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>

完整的例子

我遇到了这个问题,但为了使它适用于我的情况(在dom元素上使用拖拽(在我的情况下不是画布)),我发现你只需要在拖拽鼠标事件上使用offsetX和offsetY。

onDragOver(event){
 var x = event.offsetX;
 var y = event.offsetY;
}