在canvas标签中移动和清除线条

时间:2015-08-17 10:13:17

标签: javascript jquery css3 html5-canvas html5-audio



var isInc = true;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var counter = 0;

setInterval(function () {
    context.beginPath();
    context.moveTo(10 + counter, 10);
    context.lineTo(40, 40);
    context.lineWidth = 1;
    context.closePath();
    context.stroke();
    console.log(counter);
    if (counter == 50) isInc = false;

    else if (counter == 0) isInc = true;

    if (isInc) counter = counter + 10;
    else counter = counter - 10;
}, 1000);

<canvas id="myCanvas" width="578" height="200"></canvas>
&#13;
&#13;
&#13;

我的要求是:

我正在创建一个仪表。我画了一条像钟摆一样的线。但它创造了重复的线条。我如何删除以前的行。像这样的图像enter image description here

1 个答案:

答案 0 :(得分:2)

&#13;
&#13;
var isInc = true;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var counter = 0;
setInterval(function() {
  context.clearRect(0, 0, 578, 200);
  context.beginPath();
  context.moveTo(10 + counter, 10);
  context.lineTo(40, 40);
  context.lineWidth = 1;
  context.closePath();
  context.stroke();
  console.log(counter);
  if (counter == 50) {
    isInc = false;
  } else if (counter == 0) {
    isInc = true;
  }
  counter = isInc ? counter + 10 : counter - 10;
}, 1000);
&#13;
<canvas id="myCanvas" width="578" height="200"></canvas>
&#13;
&#13;
&#13;

.clearRect() 是必需的。