--- title: CanvasRenderingContext2D.strokeStyle slug: Web/API/CanvasRenderingContext2D/strokeStyle tags: - API - Canvas - CanvasRenderingContext2D - Property - Reference translation_of: Web/API/CanvasRenderingContext2D/strokeStyle ---
Canvas 2D API のCanvasRenderingContext2D.strokeStyle プロパティは、図形の輪郭に使用する色、グラデーション、またはパターンを指定します。デフォルト値は #000 (黒色)です。
輪郭と塗りつぶしのスタイル例については、 canvas チュートリアルの スタイルと色を適用する をご覧ください。
ctx.strokeStyle = color; ctx.strokeStyle = gradient; ctx.strokeStyle = pattern;
colorgradientpatternこのサンプルでは青色の輪郭を矩形に適用します。
<canvas id="canvas"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.strokeStyle = 'blue';
ctx.strokeRect(10, 10, 100, 100);
{{ EmbedLiveSample('Changing_the_stroke_color_of_a_shape', 700, 160) }}
この例では2つの for ループと、 {{domxref("CanvasRenderingContext2D.arc", "arc()")}} メソッドを使用して、それぞれが異なる輪郭色を持つ円のグリッドを描画します。 このためには、2つの変数 i と j を円ごとに固有となるRGB色を生成するために使用し、また緑色と青色の値だけを変更するようにします (赤色は固定値とします) 。
<canvas id="canvas" width="150" height="150"></canvas>
var 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();
}
}
結果はこのようになります:
{{EmbedLiveSample("Creating_multiple_stroke_colors_using_loops", "180", "180", "https://mdn.mozillademos.org/files/253/Canvas_strokestyle.png")}}
| 仕様書 | 策定状況 | コメント |
|---|---|---|
| {{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-strokestyle", "CanvasRenderingContext2D.strokeStyle")}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.CanvasRenderingContext2D.strokeStyle")}}
WebKit および Blinkベースのブラウザの場合、このプロパティに加えて、非標準で非推奨のメソッド ctx.setStrokeColor() が実装されています。
setStrokeColor(color, optional alpha); setStrokeColor(grayLevel, optional alpha); setStrokeColor(r, g, b, a); setStrokeColor(c, m, y, k, a);