0

How to draw a line using html5 canvas between a mousedown and mouseup of a button. Aslong as the button is clicked(mousedown), the line is drawn and stopped on mouseleave

<button id="drawLine" onmousedown="mouseDown()" onmouseup="mouseUp()">Draw 
 Line</button>
<canvas id="myCanvas" width="200" height="200" ></canvas>

var el=document.getElementById("drawLine");
var canvasEl=document.getElementById("myCanvas");
var line= canvasEl.getContext("2d");
var flag;
var count = 30;
line.beginPath();
line.moveTo(30,30)

function mouseDown(){
   flag =true;
   while(mdflag){
     line.lineTo(count++,30);
     line.stroke();
   }
}
function mouseUp(){
  flag = false;
}

1 Answers1

0

Your issue is that your while is causing an infinite loop as no other code will be able to run while your while loop is running. Thus, even when you let go of the button, your while loop will continue to run. Instead, you can use setInterval and assign it to a variable. The function inside setInterval will be called every 100 m/s and acts like a loop. Then when you let go of the mouse button, you can stop the loop (the interval) by using clearInterval().

See working example below:

var el = document.getElementById("drawLine");
var canvasEl = document.getElementById("myCanvas");
var line = canvasEl.getContext("2d");
var drawLoop;
var count = 30;
line.beginPath();
line.moveTo(30, 30)

function mouseDown() {
  drawLoop = setInterval(function() {   
      line.lineTo(count++, 30);
      line.stroke();
  }, 100);
}

function mouseUp() {
  clearInterval(drawLoop);
}
<button id="drawLine" onmousedown="mouseDown()" onmouseup="mouseUp()">Draw 
 Line</button>
<canvas id="myCanvas" width="200" height="200" style="border: 1px solid black;"></canvas>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64