The clearRect() function
Summary: The clearRect() function enables you to draw a rectangle on the canvas in which any drawings are eliminated - returning the rectangle to a transparent color
An example of filling the canvas with a red rectangle - obscuring the background image (which is 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
- The X coordinate
- The Y coordinate
- The width of the rectangle
- The height of the rectangle
An example
<script>
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);
}
</script>