我想做一个小绘画应用程序使用画布。所以我需要找到鼠标在画布上的位置。
当前回答
我尝试了所有这些解决方案,由于我的特殊设置与矩阵转换容器(panzoom库)没有工作。这将返回正确的值,即使缩放和窗格:
mouseevent(e) {
const x = e.offsetX,
y = e.offsetY
}
但前提是没有子元素。这可以通过使用CSS使它们对事件“不可见”来规避:
.child {
pointer-events: none;
}
其他回答
我遇到了这个问题,但为了使它适用于我的情况(在dom元素上使用拖拽(在我的情况下不是画布)),我发现你只需要在拖拽鼠标事件上使用offsetX和offsetY。
onDragOver(event){
var x = event.offsetX;
var y = event.offsetY;
}
我实现了另一个解决方案,我认为很简单,所以我想和你们分享一下。
所以,对我来说,问题是拖动的div将跳转到0,0的鼠标光标。所以我需要捕捉鼠标在div上的位置来调整div的新位置。
我读取的divs PageX和PageY,并设置的顶部和左侧的根据,然后得到的值,调整坐标,以保持光标在div的初始位置,我使用onDragStart监听器和存储e.nativeEvent.layerX和e.nativeEvent.layerY,只有在初始触发器给你的鼠标位置在可拖动的div。
示例代码:
onDrag={(e) => {
let newCoords;
newCoords = { x: e.pageX - this.state.correctionX, y: e.pageY - this.state.correctionY };
this.props.onDrag(newCoords, e, item.id);
}}
onDragStart={
(e) => {
this.setState({
correctionX: e.nativeEvent.layerX,
correctionY: e.nativeEvent.layerY,
});
}
我希望这能帮助那些和我经历过同样问题的人:)
通过事件可以获得画布内的鼠标坐标。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>
基于@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;
}
这适用于滚动和缩放(在这种情况下,有时它返回浮动)。
你可以买到它
var element = document.getElementById(canvasId);
element.onmousemove = function(e) {
var xCoor = e.clientX;
var yCoor = e.clientY;
}