Canvas clearRect

Summary: in this tutorial, you’ll learn how to use the clearRect() method to erase an area of the canvas.

Introduction to the Canvas clearRect() method

The clearRect() is a method of the 2D drawing context. The clearRect() method clears an area of the canvas by making that area transparent.

In practice, you draw shapes and then use the clearRect() method to clear specific areas to create some interesting effects.

The following shows the syntax of the clearRect() method:

ctx.clearRect(x, y, width, height);Code language: CSS (css)

The clearRect() has four parameters that define an area to erase:

  • x is the x-axis coordinate of the starting point of the rectangle.
  • y is the y-axis coordinate of the starting point of the rectangle.
  • width is the rectangle’s width. The sign of the width will determine the direction of the rectangle. Positive values are to the right while the negative values are to the left of the starting point.
  • height is the rectangle’s height. It also accepts both positive and negative values. Positive values are down while the negative values are up from the starting point.

The canvas clearRect() method example

The following shows the index.html that contains a canvas element:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Canvas clearRect</title>
    <link rel="stylesheet" href="css/style.css">
</head>

<body>

    <h1>JavaScript clearRect() Demo</h1>

    <canvas id="canvas" height="400" width="500">
    </canvas>

    <script src="js/app.js"></script>

</body>
</html>Code language: HTML, XML (xml)

In the app.js file, define the draw() that will draw on the canvas:

function draw() {
    const canvas = document.querySelector('#canvas');

    if (!canvas.getContext) {
        return;
    }

    const ctx = canvas.getContext('2d');

    // draw two squares
    ctx.fillStyle = '#F9DC5C';
    ctx.fillRect(50, 50, 150, 150);

    ctx.fillStyle = 'rgba(0,0,255,0.5)';
    ctx.fillRect(100, 100, 150, 150);

    // clear the intersection
    ctx.clearRect(100, 100, 100, 100);

}

draw();Code language: JavaScript (javascript)

The following picture shows the output:

And here is the clearRect() demo.

How it works.

  • First, select the canvas element using the document.querySelector() method.
  • Next, check if the browser supports the canvas API.
  • Then, get the 2D drawing context for drawing on the canvas.
  • Then, draw two intersecting squares by using the fillRect() method. The second square has alpha transparency.
  • Finally, clear the intersection of the two squares by using the clearRect() method.

Summary

  • Use the clearRect() method to set the pixels in a rectangular area on a canvas to transparent black.
Was this tutorial helpful ?