HTML5 canvas reference: The clearRect function

[No canvas support]

An example of filling the canvas with a red rectangle - obscuring the background image (set by CSS) and then clearing part of the canvas to transparency so that the background image shows through again.

The clearRect function can be used to return a section of the canvas back to transparency again - removing any drawing that might be there. It can be used to clear the canvas (assuming the dimensions are correct) without affecting the transformation matrix (ie any translate/scale/rotate/transform that you have done).

RGraph uses two functions to differentiate between using this function to clear the canvas and the way involving setting the width to itself - a Clear() function and a Reset() function. The Reset function uses the width = width method of clearing the canvas (which also removes any anti-aliasing translation that has been done).

Arguments to the function

An example

    window.onload = function ()
        var canvas  = document.getElementById("cvs");
        var context = canvas.getContext('2d');
        var width   = canvas.width;
        var height  = canvas.height;

        // Clears the whole canvas
        context.clearRect(0, 0, width, height);

RGraph on social media