Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

clearRect method

Clears the pixels on a CanvasRenderingContext2D object within a given rectangle.

HTML Canvas 2D Context, Section 8Internet Explorer 9

Syntax

CanvasRenderingContext2D.clearRect(x, y, w, h);

Parameters

x [in]

Type: number

The x-coordinate, in pixels, of the upper-left corner of the rectangle in relation to the coordinates of the canvas.

y [in]

Type: number

The x-coordinate, in pixels, of the upper-left corner of the rectangle in relation to the coordinates of the canvas.

w [in]

Type: number

The width, in pixels, of the rectangle in relation to the coordinates of the canvas.

h [in]

Type: number

The height, in pixels, of the rectangle in relation to the coordinates of the canvas.

Return value

This method does not return a value.

Standards information

Remarks

The clearRect method clears the canvas to transparent black (that is, each pixel's RGBA value is equal to zero). To clear to a specific color, use the fillRect method.

Examples

The following code example draws a filled rectangle by using fillRect and then clears the center portion by using clearRect. fillRect uses the width and height of the canvas, and clearRect uses percentages of the canvas width and height to create a frame.


<html>
<head>
<title>ClearRect example</title>
<script type="text/javascript">
    function draw() {
        var canvas = document.getElementById("MyCanvas"); // Get the canvas element.
        if (canvas.getContext) // Test for support.
        {
            var ctx = canvas.getContext("2d"); // Get the context to draw on.
            ctx.fillStyle = "black";  // Specify black as the fill color.             
            ctx.fillRect(0, 0, canvas.width, canvas.height);  // Create a filled rectangle.
        }
    }
    function clearMe() {
        var canvas = document.getElementById("MyCanvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
            // Clear the center 80% of the canvas.
            ctx.clearRect(canvas.width * .1, canvas.height * .1, canvas.width * .8, canvas.height * .8);
        }
    }
  </script>
</head>
<body onload="draw();">
  <canvas id="MyCanvas" width="600" height="500">This browser or document mode doesn't support canvas</canvas>
<p>
    <button onclick="clearMe();">clear me</button>   
    <button onclick="draw();">Reset</button>   
</p>
</body>
</html> 


See also

CanvasRenderingContext2D
fillRect

 

 

Show:
© 2014 Microsoft. All rights reserved.