使用鼠标在 HTML5 canvas 上绘图时,鼠标位置未正确定位

While drawing on a HTML5 canvas using mouse, mouse position is not correctly positioned

canvas实际高度、宽度大于样式高度、宽度。

<canvas id="canvas" class="page" width="1190" height="1683" style="height: 841.68px; width: 595.44px;"></canvas>

在这种情况下找到合适的鼠标位置时需要考虑哪些计算。 鼠标位置的当前代码是

function getMousePos(canvas, evt) {
        let ancestor = document.getElementById('viewer')
        var offsetAncestor = ancestor.getBoundingClientRect();

        var rect = canvas.getBoundingClientRect(), // abs. size of element
            scaleX = canvas.width / rect.width,    // relationship bitmap vs. element for X
            scaleY = canvas.height / rect.height;  // relationship bitmap vs. element for Y

        // return {
        //   x: (evt.clientX - rect.left) * scaleX,   // scale mouse coordinates after they have
        //   y: (evt.clientY - rect.top) * scaleY     // been adjusted to be relative to element
        // }
        return {
            x: (evt.clientX - (rect.left - offsetAncestor.left)),   // scale mouse coordinates after they have
            y: (evt.clientY - (rect.top + offsetAncestor.top))     // been adjusted to be relative to element
        }
    }

Element.getBoundingClientRect是相对视口的绝对坐标。您不需要使用容器的坐标,例如不需要 ancestor.getBoundingClientRect();

将鼠标事件客户端坐标转换为 canvas 像素坐标的示例。 (假设 Window.devicePixelRatio === 1)

const ctx = canvas.getContext("2d");
ctx.lineWidth = 10;
var x, y;
addEventListener("mousemove", mouseMove);
function mouseMove(e) {
    const canRect = canvas.getBoundingClientRect(); 
    const scaleX = canvas.width / canRect.width;  
    const scaleY = canvas.height / canRect.height; 
    const xx = (e.clientX - canRect.left) * scaleX;
    const yy = (e.clientY - canRect.top) * scaleY;
    
    if (x !== undefined) {
        ctx.beginPath();
        ctx.lineTo(x, y);
        ctx.lineTo(xx, yy);
        ctx.stroke();
    }
    x = xx;
    y = yy;
}    
canvas {
    height: 150px; 
    width: 300px;
    border: 1px solid black;
}
#viewer {
   position: absolute;
   top: 40px;
   left: 100px;
}
Move mouse over canvas.
<div id="viewer">
  <canvas id="canvas" width="1190" height="1683" style=""></canvas>
</div>