我正在尝试从鼠标侦听器中获取鼠标坐标,但它们未定义。鼠标侦听器被添加到 Canvas 并且侦听器正在触发 onMouseMove 函数,但是传递的事件似乎没有为鼠标位置定义任何 x 或 y 坐标。
我尝试了以下变量:event.pageX、event.pageY、event.clientX、event.clientY、event.x、event.y
关于我做错了什么导致鼠标坐标未定义的任何想法?谢谢你的帮助!
<script>
var boxes;
var canvas;
var context;
$(document).ready(function() {
canvas = document.getElementById("requirement_tree");
context = canvas.getContext("2d");
// Add mouse listener
canvas.addEventListener("mousemove", onMouseMove, false);
});
// Get the current position of the mouse within the provided canvas
function getMousePos(event) {
var rect = canvas.getBoundingClientRect();
if (event.pageX != undefined && event.pageY != undefined) {
x = event.pageX;
y = event.pageY;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
console.log("X:" + x);
console.log("Y:" + y);
return {
X: x - rect.left,
Y: y - rect.top
};
}
function onMouseMove(event) {
var mousePos = getMousePos(canvas, event);
var message = 'Mouse position: ' + mousePos.X + ',' + mousePos.Y;
context.font = '10pt Arial'
context.fillStyle = 'black';
context.textAlign = 'left';
context.clearRect(0, 0, 200, 200);
context.fillText(message, 100, 100);
}
</script>