javascript - 如何用javascript在按住鼠标时运行函数

标签 javascript jquery html5-canvas mousemove

我有一个 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/

相关文章:

javascript - Laravel:提交动态生成的表单字段

javascript - 这个错误说明了什么?类型 'ParsedQs' 不可分配给类型 'string'

javascript - 在 JavaScript 中的序列化数组中设置复选框值

javascript - Node 和 Redis : Redis Clients

javascript - 需要在右下角的 css div 中定位 html5 Canvas

Javascript - 获取实际渲染的字体高度

javascript - jquery运行时对象状态维护

javascript - 从 jquery 将文本框值添加到 gridview,而不使用 C#

jquery - css 类选择器不工作,不知道为什么

javascript - 是否可以让用户在玩 html/js 游戏之前选择他们的正方形(游戏组件)的颜色?