An example of using the canvas clearRect() function

Written by Richard Heyes, on 11th April 2013

A guide explaining how to use the clearRect() function to clear an area of the canvas back to transparency.


The clearRect() function 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 coloured rectangle on to the canvas. Don't confuse it with drawing a white rectangle - because the page colour 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 colour is already set to white
        context.fillStyle = 'white';

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

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

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 separate functions for them:

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

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