如何在 javascript 按住鼠标时 运行 一个函数
How to run a function when the mouse is held down with javascript
我有一个 jquery 函数,它使用 canvas 来创建线条,就像您使用画图所做的那样。当鼠标移到 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
则执行代码。这验证了左键的按下(按住鼠标)。
$("#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>
我有一个 jquery 函数,它使用 canvas 来创建线条,就像您使用画图所做的那样。当鼠标移到 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
则执行代码。这验证了左键的按下(按住鼠标)。
$("#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>