--- title: CanvasRenderingContext2D.strokeStyle slug: Web/API/CanvasRenderingContext2D/strokeStyle tags: - Canvas - CanvasRenderingContext2D translation_of: Web/API/CanvasRenderingContext2D/strokeStyle ---
CanvasRenderingContext2D.strokeStyle 是 Canvas 2D API 描述画笔(绘制图形)颜色或者样式的属性。默认值是 #000 (black)。
参见 Canvas Tutorial 中的 Applying styles and color 章节。
ctx.strokeStyle = color; ctx.strokeStyle = gradient; ctx.strokeStyle = pattern;
colorgradientpatternstrokeStyle 属性设置不同的颜色这是一段简单的代码片段,使用 strokeStyle 属性设置不同的颜色。
<canvas id="canvas"></canvas>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "blue";
ctx.strokeRect(10, 10, 100, 100);
修改下面的代码并在线查看 canvas 的变化:
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.strokeStyle = "blue"; ctx.strokeRect(10, 10, 100, 100);</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
}
reset.addEventListener("click", function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener("click", function() {
textarea.focus();
})
textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);
{{ EmbedLiveSample('Playable_code', 700, 360) }}
strokeStyle 例子这个例子使用 strokeStyle 属性改变图形轮廓线的颜色。我们使用 {{domxref("CanvasRenderingContext2D.arc", "arc()")}} 绘制圆形来代替正方形。
var ctx = document.getElementById('canvas').getContext('2d');
for (var i=0;i<6;i++){
for (var 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();
}
}
<canvas id="canvas" width="150" height="150"></canvas>
结果如下显示:
{{EmbedLiveSample("A_strokeStyle_example", "180", "180", "https://mdn.mozillademos.org/files/253/Canvas_strokestyle.png")}}
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-strokestyle", "CanvasRenderingContext2D.strokeStyle")}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.CanvasRenderingContext2D.strokeStyle")}}
ctx.setStrokeColor() 。
setStrokeColor(color, optional alpha); setStrokeColor(grayLevel, optional alpha); setStrokeColor(r, g, b, a); setStrokeColor(c, m, y, k, a);