CanvasRenderingContext2D: strokeStyle 属性
Canvas 2D API 的 CanvasRenderingContext2D.strokeStyle 属性指定用于形状描边(轮廓)的颜色、渐变或图案。默认值为 black。
值
以下之一:
color渐变-
一个
CanvasGradient对象(线性或径向渐变)。 pattern-
一个
CanvasPattern对象(重复的图像)。
示例
更改形状的描边颜色
此示例为矩形应用了蓝色描边颜色。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "blue";
ctx.strokeRect(10, 10, 100, 100);
结果
使用循环创建多个描边颜色
在此示例中,我们使用两个 for 循环和 arc() 方法绘制一个圆圈网格,每个圆圈都有不同的描边颜色。为了实现这一点,我们使用变量 i 和 j 为每个圆圈生成唯一的 RGB 颜色,并且只修改绿色和蓝色值。(红色通道具有固定值。)
js
const ctx = document.getElementById("canvas").getContext("2d");
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 6; j++) {
ctx.strokeStyle = `rgb(
0
${Math.floor(255 - 42.5 * i)}
${Math.floor(255 - 42.5 * j)})`;
ctx.beginPath();
ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true);
ctx.stroke();
}
}
结果如下所示
规范
| 规范 |
|---|
| HTML # dom-context-2d-strokestyle-dev |
浏览器兼容性
加载中…
WebKit/Blink 特定说明
在 WebKit 和 Blink 浏览器中,除了此属性外,还实现了非标准的、已弃用的 ctx.setStrokeColor() 方法。
js
setStrokeColor(color);
setStrokeColor(color, alpha);
setStrokeColor(grayLevel);
setStrokeColor(grayLevel, alpha);
setStrokeColor(r, g, b, a);
setStrokeColor(c, m, y, k, a);