YouTip LogoYouTip

Canvas Rect

## HTML Canvas `rect()` Method The `rect()` method of the HTML Canvas 2D Context API is used to create a rectangular path. It is important to note that the `rect()` method **does not** draw directly onto the canvas. Instead, it adds a rectangle to the current path. To actually render the rectangle on the screen, you must use the `stroke()` method (to draw the outline) or the `fill()` method (to fill the interior). --- ## Browser Support The `rect()` method is widely supported across 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 `` element.* --- ## Syntax and Parameters ### Syntax ```javascript context.rect(x, y, width, height); ``` ### Parameter Values | Parameter | Type | Description | | :--- | :--- | :--- | | `x` | Number | The x-coordinate of the upper-left corner of the rectangle (in pixels). | | `y` | Number | The y-coordinate of the upper-left corner of the rectangle (in pixels). | | `width` | Number | The width of the rectangle (in pixels). Can be positive or negative. | | `height` | Number | The height of the rectangle (in pixels). Can be positive or negative. | --- ## Code Examples ### Example 1: Basic Outline Rectangle This example demonstrates how to define a $150 \times 100$ pixel rectangle and draw its outline using `stroke()`. ```html Your browser does not support the HTML5 canvas tag. ``` --- ### Example 2: Drawing Multiple Rectangles with Different Styles When drawing multiple shapes, it is best practice to use `beginPath()` before defining each new shape. This ensures that style properties (like `strokeStyle` or `lineWidth`) are applied independently to each path. ```html Your browser does not support the HTML5 canvas tag. ``` --- ## Key Considerations ### 1. `rect()` vs. `fillRect()` vs. `strokeRect()` The Canvas API provides three different methods for working with rectangles. Understanding their differences is crucial for efficient rendering: * **`rect(x, y, w, h)`**: Adds a rectangle to the **current path**. It does not draw anything by itself. You must call `stroke()` or `fill()` afterward. * **`fillRect(x, y, w, h)`**: Draws a **filled** rectangle directly to the canvas immediately, bypassing the path creation process. * **`strokeRect(x, y, w, h)`**: Draws an **outlined** rectangle directly to the canvas immediately, bypassing the path creation process. ### 2. The Importance of `beginPath()` If you do not call `beginPath()` before calling `rect()`, the new rectangle will be added to the existing path. If you subsequently call `stroke()`, the browser will re-draw all previously defined shapes in the path, which can cause performance issues and unexpected style overrides.
← Canvas FillrectCanvas Miterlimit β†’