我有一个 jquery 函数,它使用 Canvas 创建线条,就像使用 Paint 一样。该功能的工作原理是当鼠标在 Canvas 上移动时画圆圈。我想更改此函数,使其仅在鼠标移动到 Canvas 上并且用户按住鼠标时运行。这是函数:
$("#canvas").mousemove(function(event) {
ctx.lineWidth = 4;
ctx.fillStyle = "fuchsia";
ctx.beginPath();
ctx.arc(event.pageX, event.pageY, 6, 0, Math.PI*2, false);
ctx.fill();
});
有没有一种至少相对直接的方法来实现这一目标?我什至不知道如何开始。任何意见将不胜感激!
最佳答案
如果event.which == 1
则执行代码。这验证了左键的按下(按住鼠标)。
了解更多MouseEvent.which
.
$("#canvas").on('mousemove',function(event) {
if(event.which == 1){
var ctx = this.getContext("2d");
ctx.lineWidth = 4;
ctx.fillStyle = "fuchsia";
ctx.beginPath();
ctx.arc(event.pageX, event.pageY, 6, 0, Math.PI*2, false);
ctx.fill();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
关于javascript - 如何用javascript在按住鼠标时运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50788544/