--- title: CanvasRenderingContext2D.setLineDash() slug: Web/API/CanvasRenderingContext2D/setLineDash translation_of: Web/API/CanvasRenderingContext2D/setLineDash ---
{{APIRef}}

The CanvasRenderingContext2D.setLineDash() method of the Canvas 2D API sets the line dash pattern.

Syntax

void ctx.setLineDash(segments);

Parameters

segments
An {{jsxref("Array")}}. A list of numbers that specifies distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. An empty array clears the dashes, so that a solid line will be drawn.

Examples

Using the setLineDash method

This is just a simple code snippet which uses the setLineDash method to draw a dashed line.

HTML

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

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.setLineDash([5, 15]);

ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(400, 100);
ctx.stroke();

Edit the code below and see your changes update live in the canvas:

{{ EmbedLiveSample('Playable_code', 700, 360) }}

Specifications

Specification Status Comment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-setlinedash", "CanvasRenderingContext2D.setLineDash")}} {{Spec2('HTML WHATWG')}}  

Browser compatibility

{{CompatibilityTable}}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatVersionUnknown}} {{ CompatGeckoDesktop(27) }} {{ CompatIE(11) }} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{ CompatGeckoMobile(27) }} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

Gecko-specific notes

WebKit-specific notes

See also