YouTip LogoYouTip

Canvas Strokerect

## HTML Canvas strokeRect() Method The `strokeRect()` method of the Canvas 2D API draws a rectangular outline (no fill) on the canvas. The default stroke color is black. To customize the appearance of the outline (such as changing its color, gradient, or pattern), use the `strokeStyle` property before calling `strokeRect()`. --- ## Syntax ```javascript context.strokeRect(x, y, width, height); ``` ### Parameter Values | Parameter | Type | Description | | :--- | :--- | :--- | | `x` | Number | The x-axis coordinate of the upper-left corner of the rectangle. | | `y` | Number | The y-axis coordinate of the upper-left corner of the rectangle. | | `width` | Number | The width of the rectangle in pixels. Positive values go to the right, while negative values go to the left. | | `height` | Number | The height of the rectangle in pixels. Positive values go down, while negative values go up. | --- ## Browser Support The `strokeRect()` method is widely supported across all modern web browsers: * Google Chrome * Mozilla Firefox * Safari * Opera * Microsoft Edge / Internet Explorer 9+ *Note: Internet Explorer 8 and earlier versions do not support the `` element.* --- ## Code Examples ### Example 1: Drawing a Basic Rectangle Outline This example draws a simple $150 \times 100$ pixel rectangle outline starting at coordinates $(20, 20)$. ```html Your browser does not support the HTML5 canvas tag. ``` ### Example 2: Styling the Rectangle Outline You can use properties like `strokeStyle` and `lineWidth` to customize the color and thickness of the outline. ```javascript var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); // Set stroke color to red and line width to 5 pixels ctx.strokeStyle = "#FF0000"; ctx.lineWidth = 5; // Draw the styled rectangle outline ctx.strokeRect(50, 50, 200, 80); ``` --- ## Key Considerations 1. **Immediate Drawing:** Unlike path-drawing methods (such as `rect()`), `strokeRect()` draws directly to the canvas immediately and does not modify the current path. This means you do not need to call `beginPath()` or `stroke()` separately. 2. **Line Width Alignment:** The stroke is centered on the path line. For example, if you set `lineWidth = 1`, the line will be drawn $0.5$ pixels inside and $0.5$ pixels outside the specified coordinates. On high-density screens or standard displays, this can sometimes cause the line to look blurry. To get crisp 1-pixel lines, offset your coordinates by $0.5$ pixels (e.g., use `x = 20.5` instead of `20`). 3. **Zero Dimensions:** If either `width` or `height` is set to `0`, the method will not draw anything.
← Canvas ClearrectCanvas Fillrect β†’