How to erase previously drawn lines on an HTML5 canvas with JavaScript?

Sometimes, we want to erase previously drawn lines on an HTML5 canvas with JavaScript.

In this article, we’ll look at how to erase previously drawn lines on an HTML5 canvas with JavaScript.

How to erase previously drawn lines on an HTML5 canvas with JavaScript?

To erase previously drawn lines on an HTML5 canvas with JavaScript, we can overwrite the previous shape with a new image.

For instance, we write:

<canvas width='200' height='200'></canvas>

to add a canvas.

And we write:

const canvas = document.querySelector('canvas')
const context = canvas.getContext('2d');

context.fillStyle = 'blue';
context.fillRect(0, 0, 100, 100);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);

context.fillStyle = 'red';
context.fillRect(50, 50, 100, 100);

setTimeout(() => {
  context.putImageData(imageData, 0, 0);
}, 1000);

to draw rectangles on the canvas with fillRect.

We use the getImageData to get the canvas content before the red rectangle is drawn.

Then after we draw the red rectangle, we call putImageData with imageData to overwrite the blue and red rectangles with the canvas content that only has the blue rectangle.

Therefore, we see the blue and red rectangle drawn for a second, then we see the blue rectangle only thereafter.

Conclusion

To erase previously drawn lines on an HTML5 canvas with JavaScript, we can overwrite the previous shape with a new image.