1

I got some lines drawn on my canvas. I want to clear it so that I can draw some new lines.
I use context.clearRect(0, 0, canvas.width, canvas.height);, just as everyone is suggesting. But when I draw some new lines, all the lines I've previously drawn reappear.
When using the canvas.width = canvas.width trick, it works as expected.

What am I missing?

markonius
  • 625
  • 6
  • 25

1 Answers1

3

You probably did not end your previous path. Make sure to call ctx.beginPath() before drawing your new lines.

const ctx = canvas.getContext('2d');
function draw()
{
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath(); // <-
  ctx.moveTo(0, 0);
  ctx.lineTo(100, 100);
  ctx.stroke();
}
function drawFaulty()
{
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.moveTo(100, 100);
  ctx.lineTo(200, 200);
  ctx.stroke();
}
<canvas id="canvas" width="200" height="200"></canvas><br/>
<button onclick="draw()">Clear and Draw</button><br/>
<button onclick="drawFaulty()">Clear and Draw - Faulty</button>
H.B.
  • 166,899
  • 29
  • 327
  • 400