Canvas Fillrect
## HTML Canvas fillRect() Method
The `fillRect()` method of the Canvas 2D API draws a filled rectangle on the canvas. The default fill color is solid black.
To customize the fill color, gradient, or pattern, you must set the `fillStyle` property before calling `fillRect()`.
---
## Syntax
```javascript
context.fillRect(x, y, width, height);
```
### Parameter Values
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `x` | Number | The x-axis coordinate of the starting point (top-left corner) of the rectangle. |
| `y` | Number | The y-axis coordinate of the starting point (top-left corner) of the rectangle. |
| `width` | Number | The width of the rectangle in pixels. Positive values go to the right, negative values go to the left. |
| `height` | Number | The height of the rectangle in pixels. Positive values go down, negative values go up. |
---
## Code Examples
### Example 1: Drawing a Basic Filled Rectangle
This example draws a standard $150 \times 100$ pixel black rectangle (default color) starting at coordinates $(20, 20)$.
```html
```
### Example 2: Drawing a Colored Rectangle
To change the color of the rectangle, set the `fillStyle` property before calling `fillRect()`.
```javascript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Set fill color to red
ctx.fillStyle = "#FF0000";
// Draw a red rectangle at (50, 50) with width 100 and height 80
ctx.fillRect(50, 50, 100, 80);
```
---
## Key Considerations & Best Practices
* **Immediate Drawing:** Unlike path-drawing methods (such as `rect()`), `fillRect()` draws directly to the canvas context immediately and does not modify the current path. This means you do not need to call `beginPath()` or `fill()` after calling `fillRect()`.
* **Coordinate System:** The canvas coordinate system starts at $(0,0)$ in the top-left corner. Increasing `x` moves the drawing to the right, and increasing `y` moves it downwards.
* **Negative Dimensions:** If you provide negative values for `width` or `height`, the rectangle will project to the left of `x` or above `y` respectively.
* **Clearing Rectangles:** If you need to clear a rectangular area instead of filling it, use the companion method `clearRect(x, y, width, height)`.
---
## Browser Support
The `fillRect()` method is supported by all modern web browsers:
* Google Chrome
* Mozilla Firefox
* Microsoft Edge / Internet Explorer 9+
* Safari
* Opera
*Note: Internet Explorer 8 and earlier versions do not support the `
YouTip