justanotherhobbyist
justanotherhobbyist

Reputation: 2190

Perfecting canvas mouse coordinates

I'm working on a function that I can use to get canvas coordinates. Works kind of well, until part of the canvas is invisible on the screen.

When i make the window small, and scroll to bottom right corner it seems to start from the visible part of the canvas. How can I fix this to get the right coordinates?

Here's my code:

function getMousePosition(event) {
var MX = new Number();
var MY = new Number();

if (event.x != undefined && event.y != undefined) {
    MX = event.x;
    MY = event.y;
}
else { // Firefox method to get the position
    MX = event.clientX + document.body.scrollLeft +
    document.documentElement.scrollLeft;
    MY = event.clientY + document.body.scrollTop +
    document.documentElement.scrollTop;
}
MX -= canvas.offsetLeft;
MY -= canvas.offsetTop;
alert("x: " + MX + "  y: " + MY);

}

Upvotes: 0

Views: 2086

Answers (1)

Endre Simo
Endre Simo

Reputation: 11541

Here is the function i get used to obtain the canvas coordinates:

function getCanvasPos(el) {
    var canvas = document.getElementById(el);
    var _x = canvas.offsetLeft;
    var _y = canvas.offsetTop;

    while(canvas = canvas.offsetParent) {
        _x += canvas.offsetLeft - canvas.scrollLeft;
        _y += canvas.offsetTop - canvas.scrollTop;
    }

    return {
        left : _x,
        top : _y
    }
};

...and here is the function for mouse coordinates

function mousePos(e) {

    var mouseX = e.clientX - getCanvasPos(e.target).left + window.pageXOffset;
    var mouseY = e.clientY - getCanvasPos(e.target).top + window.pageYOffset;
    return {
        x : mouseX,
        y : mouseY
    };
};

The mouse event listener is looking something like this:

canvas.addEventListener('mousemove', function(e){
    console.log(canvas.mousePos(e).x);
});

Upvotes: 1

Related Questions