문제

I'm attempting to take in mouse coordinates from a mouse listener but they are coming in undefined. The mouse listener is being added to the Canvas and the listener is triggering the onMouseMove function, however the event being passed doesn't seem to have any defined x or y coordinates for the mouse position.

I've tried the following variables: event.pageX, event.pageY, event.clientX, event.clientY, event.x, event.y

Any ideas on what I'm doing incorrectly to cause the mouse coordinates to come in undefined? Thanks for any help!

<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>
도움이 되었습니까?

해결책

At least, error in handler for mouseMove event. Event object transmitted in second arguments of handler.

// ...
// Get the current position of the mouse within the provided canvas
function getMousePos(element, event) {
    var rect = canvas.getBoundingClientRect();
// ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top