CanvasRenderingContext2D: stroke() 方法
Canvas 2D API 的 CanvasRenderingContext2D.stroke() 方法使用当前的描边样式来描画(描边)当前路径或给定路径。
描边是沿着路径的中心线对齐的;换句话说,一半的描边会绘制在内部,一半绘制在外部。
描边是使用 非零规则(non-zero winding rule) 进行绘制的,这意味着路径的交叉点仍会被填充。
语法
js
stroke()
stroke(path)
参数
返回值
无(undefined)。
示例
一个简单的描边矩形
此示例使用 rect() 方法创建一个矩形,然后使用 stroke() 将其绘制到画布上。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.rect(10, 10, 150, 100);
ctx.stroke();
结果
重复描画路径
通常,您希望为要描画的每个新对象调用 beginPath()。如果您不这样做,则之前的子路径将保留在当前路径中,并且每次调用 stroke() 方法时都会被描画。但在某些情况下,这可能是期望的效果。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
此代码将第一个路径描画三次,第二个路径描画两次,第三个路径描画一次。
js
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();
结果
描边和填充
如果您想同时描画和填充一个路径,执行这些操作的顺序将决定结果。在此示例中,左侧的正方形是以描边在填充之上的方式绘制的。右侧的正方形是以填充在描边之上的方式绘制的。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
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();
结果
规范
| 规范 |
|---|
| HTML # dom-context-2d-stroke-dev |
浏览器兼容性
加载中…
另见
- 定义此方法的接口:
CanvasRenderingContext2D