为什么画布中的鼠标坐标是错误的

Why the coordinates of mouse in canvas are wrong?

本文关键字:错误 坐标 鼠标 布中 为什么      更新时间:2023-09-26

>我打算在画布上用鼠标光标自由绘制。我的代码似乎用颜色完成了这部分,但是当我绘制时,它没有采用我在画布中当前鼠标位置的确切坐标。

<body>
<canvas id="canvas" style=" width: 400; height: 400px; background-color:yellow; position: absolute; margin-left:100px; margin-top:30px"></canvas>
<script>
var Color = 'blue';
var Canvas = document.getElementById('canvas');
var Context = Canvas.getContext('2d');
$("canvas").on("mousemove",function(e){
        X = e.clientX - canvas.offsetLeft;
        Y = e.clientY - canvas.offsetTop;
Context.strokeStyle = Color;
    Context.lineWidth = 3;
    Context.lineCap = 'round';
    Context.beginPath();
Context.moveTo(X,Y);
Context.lineTo(X,Y);
Context.fillRect(X,Y, 3,3)
Context.stroke();
Context.closePath();
});
</script>
</body>

https://jsfiddle.net/93L8mLnf/

我在console.log坐标中进行了测试,它们是直立的。我很困惑..

您需要将

画布的尺寸与 DOM 元素同步。添加这个:

Canvas.width = Canvas.clientWidth;
Canvas.height = Canvas.clientHeight;

示范

您还会注意到画布不再模糊。

请注意,每次画布 DOM 元素更改大小时都必须执行此操作(通常是因为窗口大小已调整),因此当您的元素大小不是固定大小时,您应该在窗口resize事件上绑定事件处理程序以再次执行该同步(并且通常重新绘制内容)。

您必须通过画布属性添加宽度和高度见小提琴

<canvas id="canvas" style="background-color:yellow;" width="250" height="250"></canvas>