HTML5 canvas在mousedown和mouseup之间画线

时间:2019-01-31 05:27:45

标签: javascript html5 html5-canvas

如何在按钮的mousedown和mouseup之间使用html5画布绘制线条。 只要单击按钮(鼠标向下),就会在鼠标左键上画线并停止

<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 个答案:

答案 0 :(得分:0)

您的问题是您的while导致了无限循环,因为您的while循环正在运行时,其他代码将无法运行。因此,即使您放开按钮,您的while循环也将继续运行。相反,您可以使用setInterval并将其分配给变量。 setInterval内部的函数将每100 m / s调用一次,就像一个循环。然后,放开鼠标按钮时,可以使用clearInterval()停止循环(间隔)。

请参见下面的工作示例:

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>