简体   繁体   中英

Getting mouse position in canvas after movement

I am using this function to convert mouse coordinates to coordinates on the canvas, but sometimes after you scroll down and then scroll back up, the mouse position on the canvas won't match up. Here's the function:

function getMousePos(x, y) {
        var rect = document.getElementById("canvas").getBoundingClientRect();
        return {
        x: x - rect.left,
        y: y - rect.top
        };
    }

If you're not using your mousemove on your canvas use this:

$(function () { 
canvas = document.getElementById('canvas');
canvas.onmousemove = mousePos;
 });

function mousePos(e) {
    if (e.offsetX) {
        mouseX = e.offsetX;
        mouseY = e.offsetY;
    }
    else if (e.layerX) {
        mouseX = e.layerX;
        mouseY = e.layerY;
    }
}

I just did something similar. I didn't account for horizontal scroll. I hope this helps.

Add onmousemove="cnvs_getCoordinates(event)" inside your html tag. Then in your javascript file:

function cnvs_getCoordinates(e)
{
    var offsetOfBox = document.getElementById('canvas').offset();

    x = e.clientX - offsetOfBox.left;
    y = e.clientY - offsetOfBox.top + $(window).scrollTop();
}

The variables x and y are the coordinates on your canvas. The only bad thing with my function is it only runs when the mouse is moved. But the math is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM