Categories
JavaScript Answers

How to Clear the Canvas for Redrawing?

Spread the love

If we have a canvas, we may want to clear it so that we can draw new things on it.

In this article, we’ll look at how to clear the canvas so that we can draw on it again.

Clear the Canvas for Redrawing

We can clear the canvas easily with the clearRect method, which is part of the canvas context object.

For instance, if we have the following HTML:

<canvas></canvas>
<button>
  clear
</button>

Then we can write:

const canvas = document.querySelector("canvas");
const button = document.querySelector("button");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "green";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

button.addEventListener('click', () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
})

to draw something and add a click listener to the button to clear the canvas when we click the button.

We call getContext to get the context object.

Then we call beginPath to start drawing.

And we set the lineWidth to set the width of the line.

strokeStyle sets the stroke style.

rect draws the rectangle with the x and y coordinates of the top left corner and the width and height respectively.

And the stroke method draws the rectangle.

Next, we call addEventListener with the 'click' to add a click listener to the button.

And the callback runs when we click the button.

We call clearRect with the canvas context with the same arguments as rect .

It clears the canvas instead of drawing on it.

Transformed Coordinates

If we added coordinate transformations to our canvas, then we’ve to add more code to save the transformation matrix first.

Then we can clear the canvas, and then restore the transformation matrix.

To do this, we write:

const canvas = document.querySelector("canvas");
const button = document.querySelector("button");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "green";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

button.addEventListener('click', () => {
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.restore();
})

In the callback, we call save to save the transformation matrix.

setTransform set the transformation to the identity matrix to remove the transformation.

Then we call clearRect to clear the canvas.

And we call restore to restore the transformation.

Conclusion

We can clear the canvas by calling the clearRect method.

If we have transformed coordinates, then we can save the transformation matrix, clear the canvas, and then restore the transformation matrix.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *