How to Clear an HTML Canvas
📣 Sponsor
When we've created a canvas, sometimes we'll want to clear it completely before redrawing something else. Let's look at how to do that.
How to clear HTML Canvas for Redrawing
Let's say we have a canvas, and we've already written code like this:
let myCanvas = document.getElementById('myCanvas');
let ctx = myCanvas.getContext('2d');
If we want to clear the entire canvas and leave it blank, we use clearRect()
. clearRect
has the 4 arguments - x
, y
, width
and height
.
If we want to clear a canvas entirely, starting at (0, 0)
, our code looks like this:
let myCanvas = document.getElementById('myCanvas');
let ctx = myCanvas.getContext('2d');
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
Although we can clear different areas if we want. The below code clears a canvas starting at the xy coordinates (150, 150), and only clearing 100px by 150px (width by height) of content:
let myCanvas = document.getElementById('myCanvas');
let ctx = myCanvas.getContext('2d');
ctx.clearRect(150, 150, 100, 150);
Clearing a HTML Canvas with a Custom Color
To clear a canvas with a custom color, you can instead use the normal rect()
function, with a custom color. That looks like this:
let myCanvas = document.getElementById('myCanvas');
let ctx = myCanvas.getContext('2d');
ctx.rect(0, 0, myCanvas.width, myCanvas.height);
// Fill our rectangle
ctx.fillStyle = 'red';
ctx.fill();
The above code will clear our canvas and fill it with red instead.
More Tips and Tricks for HTML
- How does enterkeyhint work in HTML?
- How to Draw Text with HTML Canvas
- Getting Started with HTML Canvas
- How to wrap text in HTML Canvas
- Creating Shapes with HTML Canvas
- SEO HTML Meta Tag Reference List
- Everything you need to know about HTML Input Types
- Creating Dark Mode, for Lazy People
- RGB, HSL and Lab Color Codes
- How to save HTML Canvas as an Image