An example of using the clearRect function


The clearRect does exactly what it says on the tin - it draws a see-through rectangle on to the canvas. As opposed to the rect, strokeRect or fillRect functions - which draw a colored rectangle on to the canvas. Don't confuse it with drawing a white rectangle - because the page color is (usually) white, and this function clears the rectangle that you define - it usually looks like it produces a white rectangle.

An example

Here the background image of the canvas is set by CSS and there is a black rectangle being drawn on the canvas. If the canvas was then cleared using a white rectangle the background would be obscured and you wouldn't see any RGraph logos. Instead you can use the clearRect function to draw a "clear" rectangle across the whole of the canvas - thus allowing the image to show through.

[No canvas support]
    window.onload = function (e)
        var context = document.getElementById('cvs').getContext('2d');
        // Set the fillstyle to white so that when the button is
        // pressed the color is already set to white
        context.fillStyle = 'white';

<button onclick="document.getElementById('cvs').getContext('2d').fillRect(0,0,600,250)">Clear with white rectangle</button>
<button onclick="document.getElementById('cvs').getContext('2d').clearRect(0,0,600,250)">Clear with clear rectangle</button>

Clearing the canvas by setting the width or height

You may or may not already know that another way to clear the canvas is to simply set the canvas width or height. You can do that by either assigning a new value to it or setting it to itself:

// canvas.width = 600;
canvas.width = canvas.width;

An important thing to note though is that doing this also resets the canvas transformation matrix. This means that if you've done a translate, or transform then using this method will reset that. One way to make it clear and do the right thing that you want to do is to define seperate functions for them:

function resetCanvas (canvas)
    canvas.width = canvas.width;

function clearCanvas (canvas)
    canvas.getContext('2d').clearRect(0,0,canvas.width, canvas.height);