YouTip LogoYouTip

Canvas Strokestyle

## HTML Canvas `strokeStyle` Property The `strokeStyle` property of the Canvas 2D API specifies the color, gradient, or pattern to use for the strokes (outlines) around shapes. By default, this property is set to `#000000` (solid black). --- ## Syntax ```javascript context.strokeStyle = color | gradient | pattern; ``` ### Property Values | Value | Description | | :--- | :--- | | **`color`** | A string parsing as a CSS `` value (e.g., hexadecimal, RGB, RGBA, HSL, or named colors). The default is `#000000`. | | **`gradient`** | A `CanvasGradient` object (either linear or radial) created via `createLinearGradient()` or `createRadialGradient()`. | | **`pattern`** | A `CanvasPattern` object created via `createPattern()` using an image, canvas, or video source. | --- ## Browser Support The `strokeStyle` property is fully 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 `` element.* --- ## Code Examples ### Example 1: Drawing a Rectangle with a Solid Color Stroke This example demonstrates how to draw a rectangle outline using a solid red stroke. ```html Your browser does not support the HTML5 canvas tag. ``` --- ### Example 2: Drawing a Rectangle with a Linear Gradient Stroke This example demonstrates how to create a linear gradient and apply it as the stroke style for a rectangle. ```html Your browser does not support the HTML5 canvas tag. ``` --- ### Example 3: Drawing Text with a Gradient Stroke You can also apply gradients to text outlines using `strokeText()`. ```html Your browser does not support the HTML5 canvas tag. ``` --- ## Considerations and Best Practices * **State Preservation:** The `strokeStyle` is part of the 2D drawing state. If you are changing stroke styles frequently within complex drawings, use `ctx.save()` and `ctx.restore()` to manage and revert to previous styles easily. * **Alpha Transparency:** You can apply transparency to solid colors using `rgba()` or `hsla()` values (e.g., `ctx.strokeStyle = "rgba(255, 0, 0, 0.5)"` for 50% transparent red). * **Gradient Coordinates:** When using gradients, the coordinates are relative to the canvas coordinate system, not the shape itself. Ensure your gradient coordinates align with the position of the shape you are outlining.
← Canvas ShadowcolorCanvas Fillstyle β†’