Let us say you have the following HTML canvas element.
<canvas id="myCanvas" width="200" height="100"></canvas>
First, we will get hold of the canvas by its ID.
var canvas = document.getElementById("myCanvas");
Next, we will retrieve its context, which contains all information about its present settings.
var context = canvas.getContext("2d");
Lastly, we call clearRect() function on this context to clear the rectangle.
context.clearRect(0, 0, canvas.width, canvas.height);
<script> var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.clearRect(0, 0, canvas.width, canvas.height); </script>
The above approach is very fast but does not preserve strokStyle, fillStyle, etc. But if you have used beginPath before drawing your canvas, you can also use the following commands to clear it.
context.canvas.width = context.canvas.width; OR context.canvas.height = context.canvas.height;
But this approach resets strokeStyle, fillStyle to black and can be a bit slow.
In this article, we have learnt how to clear canvas rectangle using clearRect() as well as by resetting its width/height properties. Although there are several ways to clear HTML canvas, using clearRect() is one of the fastest ways to do it, in most use cases.