javascript - 按住鼠标时在 Canvas 上的鼠标位置连续绘制矩形

标签 javascript html canvas mouse

我正在尝试使用javascript和HTML Canvas 制作一个绘图程序,我需要在鼠标所在的位置连续绘制一个圆圈,但我不太确定该怎么做。我有一个粗略的想法,但我的代码(毫不奇怪)不起作用。知道我怎样才能让它发挥作用吗?代码在这里。

<canvas width = '450' height = '450' id = 'drawing'> </canvas>
<script>
  var canvas = document.getElementById('drawing');
  var ctx = canvas.getContext('2d')
  var drawing = false
  function startmoving(){ drawing = true;}
  function stopmoving() { drawing = false;}

  function draw() {
    if (drawing == true){
      ctx.fillstyle = 'black';
      ctx.fillRect(event.clientX, event.clientY, 4, 4)
    }
    setInterval(drawing, 10);
  }
</script>

最佳答案

您需要为 Canvas 设置一个 mousedown/mouseup 和 mousemove 监听器,然后在鼠标按下时在坐标处创建并放置一个矩形,如果鼠标抬起则停止绘制。另外,clientX 和 clientY 用于页面左上角的可见部分。 pageX 和 pageY 位于页面的左上角。因此,如果你使用 clientX 和 clientY 向下滚动,它将绘制在当前页面的位置,使其看起来很奇怪。修复?使用pageX和pageY(用pageX和pageY替换clientX和clientY)!

<!DOCTYPE html>
<html>

<body>
  <canvas width='450' height='450' id='drawing'> </canvas>
  <script>
    var canvas = document.getElementById('drawing');
    var drawing = false;
    //start the drawing if the mouse is down
    canvas.addEventListener('mousedown', () => {
      drawing = true;
    })
    //stop the drawing if the mouse is up
    canvas.addEventListener('mouseup', () => {
      drawing = false;
    });
    //add an event listener to the canvas for when the user moves the mouse over it and the mouse is down
    canvas.addEventListener('mousemove', (event) => {
      var ctx = canvas.getContext('2d');
      //if the drawing mode is true (if the mouse button is down)
      if (drawing == true) {
        //make a black rectangle
        ctx.fillstyle = 'black';
        //put the rectangle on the canvas at the coordinates of the mouse
        ctx.fillRect(event.clientX, event.clientY, 4, 4)
      }
    });
  </script>
</body>

</html>

关于javascript - 按住鼠标时在 Canvas 上的鼠标位置连续绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64826723/

相关文章:

python - unicode() 参数 2 必须是字符串而不是 None

javascript - 可嵌入 mp3 播放器,在音频中提供时间导航

html - 如何将 <li> 元素符号元素向右移动?

javascript - 类型错误 : Number is not a function - when trying to use Google Maps API V3 DirectionsService

javascript - 日期选择器未使用 Angular JS 进行清理

javascript - AngularJS - 引用错误 : $ is not defined

javascript - 用鼠标旋转轮盘

Android - 触摸绘图

javascript - 一个输入的多个标签上的复选框动画

javascript - jQuery 过滤方法