HTML Canvas fillRect() Method: Filling Rectangles

The HTML Canvas fillRect() method is a fundamental drawing function that allows you to create filled rectangles on your canvas. This method is essential for building various graphical elements, from simple shapes to complex user interfaces and game elements. This guide will provide a thorough understanding of how to use the fillRect() method effectively.

What is the fillRect() Method?

The fillRect() method draws a filled rectangle. Unlike strokeRect(), which only draws the outline of a rectangle, fillRect() completely fills the rectangle with a specified color or pattern. It's a core building block for creating solid shapes on a canvas.

Syntax of fillRect()

The fillRect() method has the following syntax:

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

Where:

  • x: The x-coordinate of the top-left corner of the rectangle.
  • y: The y-coordinate of the top-left corner of the rectangle.
  • width: The width of the rectangle.
  • height: The height of the rectangle.

These coordinates and dimensions are measured in pixels, relative to the canvas's origin (0,0) at the top-left corner.

Attributes

Here's a table explaining the parameters of the fillRect() method:

Attribute Type Description
x Number The x-coordinate of the top-left corner of the rectangle.
y Number The y-coordinate of the top-left corner of the rectangle.
width Number The width of the rectangle.
height Number The height of the rectangle.

Basic Examples

Let's start with a few basic examples to understand how the fillRect() method works.

Example 1: Drawing a Single Blue Rectangle

Here's a simple example that draws a single blue rectangle on the canvas.

<canvas
  id="canvas1"
  width="200"
  height="100"
  style="border: 1px solid black;"
></canvas>

<script>
//<![CDATA[

  const canvas1 = document.getElementById("canvas1");
  const ctx1 = canvas1.getContext("2d");

  ctx1.fillStyle = "blue";
  ctx1.fillRect(10, 10, 100, 50);

//]]]]><![CDATA[>
</script>

In this example, we first obtain the canvas and its 2D rendering context. We then set the fillStyle to "blue" and use fillRect() to draw a rectangle at position (10, 10) with a width of 100 pixels and a height of 50 pixels.

Example 2: Drawing Multiple Rectangles with Different Colors

This example shows how to draw multiple rectangles with different colors:

<canvas
  id="canvas2"
  width="250"
  height="150"
  style="border: 1px solid black;"
></canvas>

<script>
//<![CDATA[

  const canvas2 = document.getElementById("canvas2");
  const ctx2 = canvas2.getContext("2d");

  ctx2.fillStyle = "red";
  ctx2.fillRect(10, 10, 70, 50);
  ctx2.fillStyle = "green";
  ctx2.fillRect(100, 10, 70, 50);
  ctx2.fillStyle = "purple";
  ctx2.fillRect(10, 80, 70, 50);

//]]]]><![CDATA[>
</script>

Here, we set the fillStyle before each call to fillRect(), allowing us to draw rectangles of different colors.

Example 3: Overlapping Rectangles

This example demonstrates how overlapping rectangles are drawn:

<canvas
  id="canvas3"
  width="200"
  height="200"
  style="border: 1px solid black;"
></canvas>

<script>
//<![CDATA[

  const canvas3 = document.getElementById("canvas3");
  const ctx3 = canvas3.getContext("2d");

  ctx3.fillStyle = "rgba(255, 0, 0, 0.5)"; // Red with 50% transparency
  ctx3.fillRect(20, 20, 100, 100);
  ctx3.fillStyle = "rgba(0, 0, 255, 0.5)"; // Blue with 50% transparency
  ctx3.fillRect(80, 80, 100, 100);

//]]]]><![CDATA[>
</script>

In this case, we use rgba() colors to set transparency. Notice how the blue rectangle overlaps the red one. The order in which the rectangles are drawn affects how they overlap.

Combining with Other Canvas Functions

The fillRect() method can be used in combination with other Canvas functions to create more advanced effects:

Example 4: Using fillRect() with Transformations

Here is an example of using fillRect() along with translate() and rotate().

<canvas
  id="canvas4"
  width="200"
  height="200"
  style="border: 1px solid black;"
></canvas>

<script>
//<![CDATA[

  const canvas4 = document.getElementById("canvas4");
  const ctx4 = canvas4.getContext("2d");

  ctx4.fillStyle = "orange";
  ctx4.translate(100, 100); // Move the origin to the center
  ctx4.rotate(Math.PI / 4);  // Rotate the canvas by 45 degrees
  ctx4.fillRect(-50, -50, 100, 100); // Draw a square centered at the translated origin

//]]]]><![CDATA[>
</script>

In this example, we first translate and rotate the canvas, then we draw a square centered around the new origin using negative coordinates, which creates a rotated square.

Real-World Applications

The fillRect() method is crucial in many real-world scenarios, such as:

  • Game Development: Creating backgrounds, platforms, and other game elements.
  • Data Visualization: Drawing bars in bar charts or areas in stacked area charts.
  • User Interfaces: Building buttons, menus, and other UI components.
  • Art and Design: Creating abstract patterns, geometric shapes, and other designs.
  • Animation: Constructing animated objects by redrawing rectangles in different positions and sizes.

Tips and Best Practices

  • Set fillStyle Before fillRect(): Always set the fillStyle (or strokeStyle for strokeRect()) before calling fillRect() to ensure the correct color or pattern is applied.
  • Use rgba() for Transparency: Use rgba() color values to create transparent or semi-transparent rectangles.
  • Understand Coordinate System: The x and y coordinates in fillRect() refer to the top-left corner of the rectangle.
  • Performance: For simple rectangles, fillRect() is generally efficient. However, for more complex shapes, consider using paths.
  • Experiment: Try different values for position, size, and color to explore the possibilities.

Conclusion

The fillRect() method is a fundamental and versatile tool in the HTML Canvas API. By understanding how to use it effectively, you can create a wide variety of visual elements, from simple filled shapes to more advanced graphics. Combining it with other Canvas methods opens up a world of creative possibilities. This comprehensive guide should equip you with the necessary skills to harness the power of the fillRect() method in your web projects. Happy drawing!