W3cubDocs

/DOM

CanvasRenderingContext2D.stroke

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.

Syntax

void ctx.stroke();
void ctx.stroke(path);

Parameters

path
A Path2D path to stroke.

Examples

A simple stroked rectangle

This example creates a rectangle using the rect() method, and then draws it to the canvas using stroke().

HTML

<canvas id="canvas"></canvas>

JavaScript

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.rect(10, 10, 150, 100);
ctx.stroke();

Result

Re-stroking paths

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.

HTML

<canvas id="canvas"></canvas>

JavaScript

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();

Result

Specifications

Browser compatibilityUpdate compatibility data on GitHub

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 ? ? ?

See also

© 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