The CanvasRenderingContext2D
.lineCap
property of the Canvas 2D API determines the shape used to draw the end points of lines.
See also the chapter Applying styles and color in the Canvas tutorial.
ctx.lineCap = "butt" || "round" || "square";
"butt"
"round"
"square"
lineCap
propertyThis is just a simple code snippet using the lineCap
property to draw lines with a rounded end.
<canvas id="canvas"></canvas>
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineWidth = 15; ctx.lineCap = 'round'; ctx.lineTo(100, 100); ctx.stroke();
Edit the code below to see your changes update live in the canvas:
In this example three lines are drawn, each with a different value for the lineCap
property. Two guides to see the exact differences between the three are added. Each of these lines starts and ends exactly on these guides.
The line on the left uses the default "butt"
option. It's drawn completely flush with the guides. The second is set to use the "round"
option. This adds a semicircle to the end that has a radius half the width of the line. The line on the right uses the "square"
option. This adds a box with an equal width and half the height of the line thickness.
var ctx = document.getElementById('canvas').getContext('2d'); var lineCap = ['butt','round','square']; // Draw guides ctx.strokeStyle = '#09f'; ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(140, 10); ctx.moveTo(10, 140); ctx.lineTo(140, 140); ctx.stroke(); // Draw lines ctx.strokeStyle = 'black'; for (let i = 0; i < lineCap.length; i++) { ctx.lineWidth = 15; ctx.lineCap = lineCap[i]; ctx.beginPath(); ctx.moveTo(25 + i * 50, 10); ctx.lineTo(25 + i * 50, 140); ctx.stroke(); }
Screenshot | Live sample |
---|---|
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'CanvasRenderingContext2D.lineCap' in that specification. | Living Standard |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | 12 | Yes | Yes | Yes | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
ctx.setLineCap()
is implemented in addition to this property.CanvasRenderingContext2D
CanvasRenderingContext2D.lineWidth
CanvasRenderingContext2D.lineJoin
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap