HTML Canvas - clearRect() Method



The HTML Canvas clearRect() method can be used to erase the pixel data in the given area and from the point given by the parameters.

It is from the interface CanvasRenderingContext2D and makes the given area completely white. It should be clearly defined to avoid any errors resulting in not working of the method.

When this method is called, the co-ordinates passed is taken as the top left co-ordinates of the rectangle area which is made transparent black.

Syntax

Following is the syntax of HTML Canvas clearRect() method −

CanvasRenderingContext2D.clearRect(x, y, width, height);

Parameters

Following is the list of parameters of this method −

S.No Parameters and Description
1 x

The x co-ordinate value of the starting point of the rectangle.

2 y

The y co-ordinate value of the starting point of the rectangle

3 width

The width of the drawing rectangle.

4 height

The height of the drawing rectangle.

Return values

When the method is called, the rectangular area formed by the given parameters is taken and the pixels are changed to white.

Example

The following example creates a filled rectangle and shows how the HTML Canvas clearRect() method removes the area from the rectangle.

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById("canvas");
         var context = canvas.getContext('2d');
         context.fillStyle = 'orange';
         context.fillRect(10, 10, 250, 180);
         context.clearRect(30, 30, 50, 50);
      </script>
   </body>
</html>

Output

The output returned by the above code on webpage as −

HTML Canvas ClearRect() Method

Example

The following example creates a filled rectangle with same width and height of the canvas element and shows how clearRect() method can be used to design simple shapes.

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Reference API</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById("canvas");
         var context = canvas.getContext('2d');
         context.fillRect(0, 0, 300, 200);
         context.clearRect(10, 100, 280, 10);
         context.clearRect(150, 10, 10, 180);
      </script>
   </body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas ClearRect() Method
html_canvas_rectangles.htm
Advertisements