clear canvas in javascript

How to Clear Canvas for Redrawing in JavaScript

Often web developers use canvas for drawing simple as well as complex drawings on their web pages. But if you want to redraw things on your canvas you will need to clear the canvas. Many beginner web developers try to create a new canvas or background instead. If you want to redraw images on the same canvas, it is advisable to clear canvas. In this article, we will learn how to clear canvas for redrawing in JavaScript.


How to Clear Canvas for Redrawing in JavaScript

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);

To summarize, here is the JavaScript code to clear an HTML canvas.

<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.

Also read:

How to Use Decimal Step Value for Range in Python
How to Get Browser Viewport Dimensions in JS
How to Auto Resize TextArea to Fit Text
How to Render HTML in Text Area
How to Install PuTTy on Linux

Leave a Reply

Your email address will not be published.