简体   繁体   English

移动后在画布中获取鼠标位置

[英]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:如果您不在画布上使用 mousemove,请使用以下命令:

$(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.在 html 标签中添加onmousemove="cnvs_getCoordinates(event)" Then in your javascript file:然后在你的 javascript 文件中:

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.变量 x 和 y 是画布上的坐标。 The only bad thing with my function is it only runs when the mouse is moved.我的功能唯一不好的是它只在鼠标移动时运行。 But the math is the same.但数学是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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