fillRect() Method

The fillRect() method is used to draw a filled rectangle. The color is defined using the fillStyle property.

Syntax

context.fillRect( x, y, width, height );

Attributes

  • x: The x-coordinate in fillRect is one of the parameters of the upper-left corner of the rectangle.
  • y: The y-coordinate in fillRect is one of the parameters of the upper-left corner of the rectangle.
  • width: The width of the rectangle, in pixels.
  • height: The height of the rectangle, in pixels.

Example 1: The example shows the rectangle on canvas using fillRect().

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>HTML Canvas Rectangle</title>
    <link rel="stylesheet"
          href="style.css">
</head>
  
<body>
    <div class="box">
          w3wiki
      </div>
    <div class="textele">
          HTML Canvas Rectangle 
      </div>
      
    <canvas height="500" 
            width="500" 
            id="canvas-element">
      </canvas>
    <script src="script.js"></script>
</body>
  
</html>


CSS




@import url(
'https://fonts.googleapis.com/css2?family=Poppins&display=swap');
  
body {
    font-family: 'Poppins', sans-serif;
}
  
.box {
    font-size: 40px;
    color: green;
}
  
#canvas-element {
    border: 2px solid black;
}
.textele{
    font-size: 20px;
}


Javascript




const canvas_element = 
    document.getElementById("canvas-element");
const context = 
    canvas_element.getContext("2d");
  
// For Yellow Rectangle
  
context.fillStyle = "yellow";
context.fillRect(10, 10, 100, 100)
  
// For Blue Rectangle
  
context.fillStyle = "blue";
context.fillRect(100, 100, 100, 100)
  
// For Red Rectangle
  
context.fillStyle = "red";
context.fillRect(200, 200, 100, 100)


Output:

HTML Canvas Rectangles using fillRect()

HTML Canvas Rectangles

The HTML Canvas Rectangles facilitate the rect() method to draw rectangles on canvas. There are various attributes in the rect(x, y, width, height) method such as x and y defining the coordinates of the upper-left corner of the rectangle, width defining the width of the rectangle, and height defining the height of the rectangle.

Similar Reads

fillRect() Method

The fillRect() method is used to draw a filled rectangle. The color is defined using the fillStyle property....

strokeRect() Method

...

clearRect() Method

...