我开始尝试使用画布,这可能是一个基本问题,但在这里找不到问题。
我的鼠标光标比我在画布上使用鼠标事件坐标绘制的线慢。我在这里想念什么?
PS-如果使用jQuery的鼠标事件,则存在相同的问题:http : //jsfiddle.net/2q4Sd/2/
window.addEvent('mousemove', function (event) {
draw(event.event.clientX);
});
function draw(mouseX) {
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
ctx.moveTo(mouseX, 0);
ctx.lineTo(mouseX, canvas.height);
ctx.stroke();
ctx.closePath();
}
您的画线已关闭有两个原因。两者都与event.clientX
etc返回的坐标与画布使用的坐标之间的差异有关:
event.clientX
但是相对于“客户区域”(基本上是视口,或者在iframe的情况下,它是页面上占据的区域)进行度量。因此,当您传递event.clientX
到你的draw()
函数,并用它来画到画布上,你不是在这两个坐标系走的是差异的帐户。为此,您可以使用类似:.getBoundingClientRect()的方法。event.clientX
特定画布元素使用的坐标的比例之间可能存在差异,并且在您的情况下也存在差异。我在这里讨论了这个问题:https : //stackoverflow.com/a/19079320/1937302但是,基本上,除非您有充分的理由,否则我将确保CSS设置的画布尺寸等于使用HTML属性width
和进行设置height
。解决这两个问题都可以:
相关HTML:
<canvas style="width:400px;height:300px;" width="400" height="300"></canvas>
新draw()
功能:
function draw(mouseX) {
// fixes offset caused by event.clientX and the canvas element
// having different origins for their coordinate systems:
var xCoord = mouseX - canvas.getBoundingClientRect().left;
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
ctx.moveTo(xCoord, 0);
ctx.lineTo(xCoord, canvas.height);
ctx.stroke();
ctx.closePath();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句