CanvasRenderingContext2D.lineCap - Web APIs 编辑

The CanvasRenderingContext2D.lineCap property of the Canvas 2D API determines the shape used to draw the end points of lines.

Note: Lines can be drawn with the stroke()strokeRect(), and strokeText() methods.

Syntax

ctx.lineCap = "butt" || "round" || "square";

Options

"butt"
The ends of lines are squared off at the endpoints. Default value.
"round"
The ends of lines are rounded.
"square"
The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness.

Examples

Changing the shape of line caps

This example rounds the end caps of a straight line.

HTML

<canvas id="canvas"></canvas>

JavaScript

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineWidth = 15;
ctx.lineCap = 'round';
ctx.lineTo(100, 100);
ctx.stroke();

Result

Comparison of line caps

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.

<canvas id="canvas" width="150" height="150"></canvas>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const 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();
}
ScreenshotLive sample

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'CanvasRenderingContext2D.lineCap' in that specification.
Living Standard 

Browser compatibility

BCD tables only load in the browser

  • In WebKit- and Blink-based Browsers, a non-standard and deprecated method ctx.setLineCap() is implemented in addition to this property.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:124 次

字数:6374

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文