按住鼠标时,在鼠标所在位置的 canvas 上连续绘制矩形

Continuously draw rectangles on a canvas at the location of a mouse while the mouse is held down

我想用javascript和HTMLcanvas做一个画图程序,需要在鼠标所在的位置连续画一个圆,我我不确定该怎么做。我有一个粗略的想法,但我的代码(不足为奇)不起作用。知道如何让它工作吗?代码在这里。

<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>