Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么画布上的鼠标坐标是错误的?_Javascript_Html_Canvas - Fatal编程技术网

Javascript 为什么画布上的鼠标坐标是错误的?

Javascript 为什么画布上的鼠标坐标是错误的?,javascript,html,canvas,Javascript,Html,Canvas,我打算在画布上用鼠标光标自由绘制。我的代码似乎用颜色来完成这部分,但在我画图时,它并没有获得我当前鼠标在画布上的位置的精确坐标 <body> <canvas id="canvas" style=" width: 400; height: 400px; background-color:yellow; position: absolute; margin-left:100px; margin-top:30px"></canvas> <script>

我打算在画布上用鼠标光标自由绘制。我的代码似乎用颜色来完成这部分,但在我画图时,它并没有获得我当前鼠标在画布上的位置的精确坐标

<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>

var Color='蓝色';
var Canvas=document.getElementById('Canvas');
var Context=Canvas.getContext('2d');
$(“画布”)。在(“鼠标移动”上,函数(e){
X=e.clientX-canvas.offsetLeft;
Y=e.clientY-canvas.offsetTop;
Context.strokeStyle=颜色;
Context.lineWidth=3;
Context.lineCap='round';
Context.beginPath();
上下文。移动到(X,Y);
lineTo(X,Y);
Context.fillRect(X,Y,3,3)
stroke();
closePath();
});


我在
console.log中测试了坐标,它们是正确的。我很困惑

您需要将画布的维度与DOM元素同步。 添加以下内容:

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

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


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

您必须通过画布属性添加宽度和高度



不要通过CSS设置画布的宽度和高度,使用它的
.width
.height
属性。我明白了,现在它可以完美地工作了!谢谢你教我怎么做实际上,通过增加宽度和高度,而不是通过样式,它的工作方式应该是这样的。作为一个新手,我很难理解为什么会这样做。通常这不是一个解决方案,因为你失去了CSS调整画布大小的能力。“在我看来,这个答案是错误的。”DenysSéguret,这是有争议的。您的解决方案仅适用于已在文档中追加和呈现的画布,而不适用于缓冲区画布。
<canvas id="canvas" style="background-color:yellow;" width="250" height="250"></canvas>