HTML5 Canvas Mouse Listener坐标未定义

时间:2013-11-14 13:36:54

标签: javascript jquery html5 canvas mousemove

我正在尝试从鼠标监听器中获取鼠标坐标,但它们未定义。鼠标侦听器正被添加到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>

1 个答案:

答案 0 :(得分:0)

至少,mouseMove事件的处理程序出错。事件对象在处理程序的第二个参数中传输。

// ...
// Get the current position of the mouse within the provided canvas
function getMousePos(element, event) {
    var rect = canvas.getBoundingClientRect();
// ...