YouTip LogoYouTip

Canvas Stroke

## HTML Canvas stroke() Method The `stroke()` method is a fundamental part of the HTML5 Canvas 2D Context API. It is used to actually draw (render) the path you have defined using methods like `moveTo()`, `lineTo()`, `arc()`, or `rect()`. By default, the path is drawn as a solid black line with a width of 1 pixel. --- ## Definition and Usage When you define a path in Canvas using drawing commands (such as `moveTo()` and `lineTo()`), you are creating an invisible mathematical outline. The `stroke()` method is what makes this outline visible on the screen by tracing it with a pen. * **Default Color:** Black (`#000000`) * **Default Line Width:** 1 pixel * **Customization:** You can change the appearance of the stroke (color, gradient, or pattern) using the `strokeStyle` property, and the thickness using the `lineWidth` property before calling `stroke()`. --- ## Syntax ```javascript context.stroke(); ``` ### Parameters This method does not accept any parameters. --- ## Browser Support The `stroke()` 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 Simple Red "L" Shape This example demonstrates how to define a path consisting of two connected lines and render it in red. ```html Your browser does not support the HTML5 canvas tag. ``` ### Example 2: Customizing Stroke Width and Line Join You can combine `stroke()` with other context properties to create thicker lines with styled corners. ```javascript var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.moveTo(100, 20); ctx.lineTo(150, 100); ctx.lineTo(200, 20); ctx.strokeStyle = "blue"; // Set stroke color to blue ctx.lineWidth = 10; // Set line thickness to 10 pixels ctx.lineJoin = "round"; // Round the corners where lines meet ctx.stroke(); // Render the styled path ``` --- ## Key Considerations 1. **Always Use `beginPath()`:** When drawing multiple shapes or lines with different styles, always call `beginPath()` before starting a new shape. If you omit `beginPath()`, every time you call `stroke()`, the canvas will re-draw all previous paths along with the new one, which can cause performance issues and unexpected styling bugs. 2. **Stroke vs. Fill:** * Use `stroke()` to draw the **outline** of a shape. * Use `fill()` to paint the **interior** of a closed shape.
← Canvas BeginpathCanvas Createlineargradient β†’