HTML5 Tutorial: How to Empty or Clear your Drawing Canvas
In HTML5 we have been given a great drawing canvas that allows you to draw directly on a webpage itself. These drawings can be static and drawn just once when you load the webpage but they can also be dynamic and change all the time! Sometimes you want to empty or clear your drawing canvas to draw something else.
In this tutorial I'll show you how to do just that: with a simple method call you can empty your HTML5 drawing canvas and reset it to its background color. I will also show that it is not very different from clearing just a part of your canvas, if that is what you wish to do.
You can empty or clear your HTML5 drawing canvas by using the following method call:
ctx.clearRect(0, 0, width, height);
where width and height are the width and height of your canvas respectively. We have a canvas of 300 by 300 pixels so we need to use the following method call:
ctx.clearRect(0, 0, 300, 300);
You are now clearing a rectangle that starts at the coordinate (0, 0) with dimensions 300 by 300 pixels. Those are the dimensions of your canvas and that means you are clearing your whole HTML drawing canvas. The canvas will now be empty and it will be colored using the background color. This is usually white but you can change the background color of a canvas by using CSS styling.
How to empty a part of the HTML5 drawing canvas?
You can use the same method call to only empty a part of the canvas. You can give the top-left coordinates and dimensions of a rectangle or square and that part of the canvas will be cleared. For example, the following piece of code will clear a rectangle located at the coordinate (50, 50) with a width of 200 and a height of 100:
ctx.clearRect(50, 50, 200, 100);
Web design books
Other HTML5 drawing tutorials by Simeon Visser
- HTML5 Tutorial: Text Drawing with Fancy Colors and Effects
You can do much more than just drawing text in HTML5! In this tutorial I'll show various effects to make some fancy texts, including shadows, gradients and rotation.
- HTML5 Tutorial: Drawing Circles and Arcs on Canvas
Drawing circles and arcs in HTML5 can be quite a challenge. In this tutorial I explain how to draw circles and arcs and how the angles of arcs are measured. This tutorial contains many examples.