Danish Khan
Danish Khan

Reputation: 143

moving and clear line in canvas tag

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>

My requirement is:

I am creating a meter. I draw a line like pendulum.But it is creating duplicate line. How i remove previous lines. like this Imageenter image description here

Upvotes: 0

Views: 864

Answers (1)

Tahir Ahmed
Tahir Ahmed

Reputation: 5737

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);
<canvas id="myCanvas" width="578" height="200"></canvas>

.clearRect() was needed.

Upvotes: 2

Related Questions