CanvasRenderingContext2D.stroke() - Web APIs 编辑

The CanvasRenderingContext2D.stroke() method of the Canvas 2D API strokes (outlines) the current or given path with the current stroke style.

Strokes are aligned to the center of a path; in other words, half of the stroke is drawn on the inner side, and half on the outer side.

The stroke is drawn using the non-zero winding rule, which means that path intersections will still get filled.

Syntax

void ctx.stroke();
void ctx.stroke(path);

Parameters

path
A Path2D path to stroke.

Examples

A simple stroked rectangle

This example creates a rectangle using the rect() method, and then draws it to the canvas using stroke().

HTML

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

JavaScript

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.rect(10, 10, 150, 100);
ctx.stroke();

Result

Re-stroking paths

Typically, you'll want to call beginPath() for each new thing you want to stroke. If you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the stroke() method. In some cases, however, this may be the desired effect.

HTML

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

JavaScript

This code strokes the first path three times, the second path two times, and the third path only once.

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

// First sub-path
ctx.lineWidth = 26;
ctx.strokeStyle = 'orange';
ctx.moveTo(20, 20);
ctx.lineTo(160, 20);
ctx.stroke();

// Second sub-path
ctx.lineWidth = 14;
ctx.strokeStyle = 'green';
ctx.moveTo(20, 80);
ctx.lineTo(220, 80);
ctx.stroke();

// Third sub-path
ctx.lineWidth = 4;
ctx.strokeStyle = 'pink';
ctx.moveTo(20, 140);
ctx.lineTo(280, 140);
ctx.stroke();

Result

Stroking and filling

If you want to both stroke and fill a path, the order in which you perform these actions will determine the result. In this example, the square on the left is drawn with the stroke on top of the fill. The square on the right is drawn with the fill on top of the stroke.

HTML

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

JavaScript

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

ctx.lineWidth = 16;
ctx.strokeStyle = 'red';

// Stroke on top of fill
ctx.beginPath();
ctx.rect(25, 25, 100, 100);
ctx.fill();
ctx.stroke();

// Fill on top of stroke
ctx.beginPath();
ctx.rect(175, 25, 100, 100);
ctx.stroke();
ctx.fill();

Result

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also

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

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

发布评论

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

词条统计

浏览:125 次

字数:6072

最后编辑:7 年前

编辑次数:0 次

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