【问题标题】:Html5 canvas draw line between mousedown and mouseupHtml5画布在mousedown和mouseup之间画线
【发布时间】:2019-01-31 05:27:44
【问题描述】:

如何使用 html5 画布在按钮的 mousedown 和 mouseup 之间画一条线。 只要单击按钮(mousedown),就会绘制线条并在鼠标离开时停止

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

【问题讨论】:

标签: javascript html html5-canvas


【解决方案1】:

您的问题是您的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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多