The CanvasRenderingContext2D
.stroke()
method of the Canvas 2D API strokes (outlines) the current or given path with the current stroke style using the non-zero winding rule.
void ctx.stroke(); void ctx.stroke(path);
path
Path2D
path to stroke.This example creates a rectangle using the rect()
method, and then draws it to the canvas using stroke()
.
<canvas id="canvas"></canvas>
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke();
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.
<canvas id="canvas"></canvas>
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 = 25; ctx.strokeStyle = 'orange'; ctx.moveTo(20, 20); ctx.lineTo(160, 20); ctx.stroke(); // Second sub-path ctx.lineWidth = 13; ctx.strokeStyle = 'green'; ctx.moveTo(20, 80); ctx.lineTo(220, 80); ctx.stroke(); // Third sub-path ctx.lineWidth = 3; ctx.strokeStyle = 'pink'; ctx.moveTo(20, 140); ctx.lineTo(280, 140); ctx.stroke();
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'CanvasRenderingContext2D.stroke' in that specification. | Living Standard |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | 12 | Yes | Yes | Yes | Yes |
Path parameter |
Yes | Yes | 31 | No | Yes | No |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
Path parameter |
? | ? | Yes | 31 | ? | ? | ? |
CanvasRenderingContext2D
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/stroke