我想做一个小绘画应用程序使用画布。所以我需要找到鼠标在画布上的位置。
当前回答
关于这个问题的难点可以在这里找到:http://www.quirksmode.org/js/events_properties.html#position
使用这里描述的技术,您可以在文档中找到鼠标的位置。然后你只需检查它是否在元素的边界框内,你可以通过调用element. getboundingclientrect()来找到它,它将返回一个具有以下属性的对象:{bottom, height, left, right, top, width}。由此,判断偶数是否发生在元素内部是很简单的。
其他回答
通过事件可以获得画布内的鼠标坐标。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;
}
这适用于滚动和缩放(在这种情况下,有时它返回浮动)。
在纯javascript中没有答案,当reference元素嵌套在其他可以具有绝对定位的元素中时,返回相对坐标。下面是针对这种情况的解决方案:
function getRelativeCoordinates (event, referenceElement) {
const position = {
x: event.pageX,
y: event.pageY
};
const offset = {
left: referenceElement.offsetLeft,
top: referenceElement.offsetTop
};
let reference = referenceElement.offsetParent;
while(reference){
offset.left += reference.offsetLeft;
offset.top += reference.offsetTop;
reference = reference.offsetParent;
}
return {
x: position.x - offset.left,
y: position.y - offset.top,
};
}
基于@Patrick Boos的解决方案,但修复了中间滚动条的潜在问题。
export function getRelativeCoordinates(event: MouseEvent, referenceElement: HTMLElement) {
const position = {
x: event.pageX,
y: event.pageY,
};
const offset = {
left: referenceElement.offsetLeft,
top: referenceElement.offsetTop,
};
let reference = referenceElement.offsetParent as HTMLElement;
while (reference) {
offset.left += reference.offsetLeft;
offset.top += reference.offsetTop;
reference = reference.offsetParent as HTMLElement;
}
const scrolls = {
left: 0,
top: 0,
};
reference = event.target as HTMLElement;
while (reference) {
scrolls.left += reference.scrollLeft;
scrolls.top += reference.scrollTop;
reference = reference.parentElement as HTMLElement;
}
return {
x: position.x + scrolls.left - offset.left,
y: position.y + scrolls.top - offset.top,
};
}
我尝试了所有这些解决方案,由于我的特殊设置与矩阵转换容器(panzoom库)没有工作。这将返回正确的值,即使缩放和窗格:
mouseevent(e) {
const x = e.offsetX,
y = e.offsetY
}
但前提是没有子元素。这可以通过使用CSS使它们对事件“不可见”来规避:
.child {
pointer-events: none;
}