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

Viewed 406

I'm trying to make a drawing program using javascript and the HTML canvas, and I need to continuously draw a circle at the location of the mouse, and I'm not exactly sure how to do it. I have a rough idea but my code (not surprisingly) doesn't work. Any idea how I can make it work? the code is here.

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

1 Answers

You need set a mousedown/mouseup and mousemove listener for the canvas, then make and place a rectangle at the coordinates if the mouse is down, and stop the drawing if the mouse is up. Also, clientX and clientY are for the top left visible part of the page. pageX and pageY are for the top left of the page. So if you scroll down with clientX and clientY, it will draw at the position of the current page, making it appear weird. A fix? Use pageX and pageY (replace clientX and clientY with pageX and pageY)!

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

Related