YouTip LogoYouTip

Canvas Linecap

## HTML Canvas `lineCap` Property The `lineCap` property of the HTML5 Canvas 2D context determines the shape and style of the end caps applied to the ends of lines. By default, lines are drawn with flat, squared-off ends. By changing the `lineCap` property, you can round the ends or extend them with a square cap. --- ## Browser Support The `lineCap` property 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.* --- ## Definition and Usage The `lineCap` property sets or returns the style of the end caps for a line. ### Syntax ```javascript context.lineCap = "butt" | "round" | "square"; ``` ### Property Values | Value | Description | | :--- | :--- | | **`butt`** | **Default.** A flat edge is added to each end of the line. The line does not extend past its actual coordinate endpoints. | | **`round`** | A semi-circular cap is added to each end of the line. The radius of the cap is equal to half of the line's width. This extends the line slightly. | | **`square`** | A square cap is added to each end of the line. The cap extends the line by a length equal to half of the line's width. | --- ## Important Considerations * **Line Extension:** Both `"round"` and `"square"` values make the rendered line slightly longer than its actual coordinate length. The line is extended at both ends by an amount equal to half of the line's width (`lineWidth / 2`). * **Context State:** The `lineCap` property is a state variable of the 2D context. Once set, it applies to all paths drawn afterward until it is changed again. --- ## Code Examples ### Example 1: Comparing the Three `lineCap` Styles The following example demonstrates how the three different `lineCap` values affect the appearance and length of lines. To make the length difference clear, guide lines are drawn at the start and end coordinates of the paths. ```html Your browser does not support the HTML5 canvas tag. ``` ### Example 2: Basic Implementation A simple implementation showing how to draw a single vertical line with rounded ends: ```javascript var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.lineWidth = 15; ctx.lineCap = "round"; // Set the cap style to round ctx.moveTo(50, 20); ctx.lineTo(50, 200); ctx.stroke(); ```
← Canvas LinejoinCanvas Addcolorstop β†’