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

时间:2016-01-19 10:38:16

标签: javascript html5 canvas

我打算用画布中的鼠标光标自由绘制。我的代码似乎用颜色做了部分,但是当我绘制时它不会占用我画布中当前鼠标位置的精确坐标。

<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坐标测试,他们是核心。我很困惑..

2 个答案:

答案 0 :(得分:3)

您需要将画布的尺寸与DOM元素同步。 加上这个:

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

Demonstration

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

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

答案 1 :(得分:1)

您必须按画布属性添加宽度和高度 see in fiddle

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