在 canvas 上获取 canvas 鼠标位置

get canvas mouse position on canvas

** 在标记为重复之前阅读! **

获取 canvas 上的鼠标位置几乎可以正常工作。

我的 window 尺码是 800 x 600

我的 canvas 尺码是 400 x 300:

canvas.width = 400;
canvas.height = 300;

我的 canvas css 尺码是 100% x 100%:

canvas {width: 100vw; height: 100vh;}

问题是:如果我的鼠标在 canvas 的中间,我得到这个鼠标位置:400, 300。如果我的 window 尺码是 1600 x 1200 我会得到 800, 600.

我想获取鼠标的canvas位置。我的意思是,无论 window 大小如何,我都希望获得 200, 150

我该怎么做? 感谢您的帮助。

您必须创建从模型坐标到屏幕坐标的转换并返回。这里有很好的解释:http://www.ckollars.org/canvas-two-coordinate-scales.html

您可以将其粘贴到您的代码中。

document.getElementById("canvasId").addEventListener('mousemove',function(event){mousePos(event);});
function getMousePos(e){
    var rect = canvas.getBoundingClientRect();
    //this gets your canvas size.
    return {
        x: Math.round(e.clientX - rect.left),
        y: Math.round(e.clientY - rect.top)
    };
function mousePos(e){
    var pos = getMousePos(e);
    var mouseX = pos.x;
    var mouseY = pos.y;
}

那么您可以在其他地方引用 mouseX 和 mouseY。

//enter the rest of your code here.