--- title: CanvasRenderingContext2D.setLineDash() slug: Web/API/CanvasRenderingContext2D/setLineDash translation_of: Web/API/CanvasRenderingContext2D/setLineDash ---
The CanvasRenderingContext2D.setLineDash() method of the Canvas 2D API sets the line dash pattern.
void ctx.setLineDash(segments);
segments[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.setLineDash methodThis is just a simple code snippet which uses the setLineDash method to draw a dashed line.
<canvas id="canvas"></canvas>
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:
<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.setLineDash([5, 15]); ctx.beginPath(); ctx.moveTo(0,100); ctx.lineTo(400, 100); ctx.stroke();</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) }}
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-setlinedash", "CanvasRenderingContext2D.setLineDash")}} | {{Spec2('HTML WHATWG')}} |
{{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}} |
mozDash has been implemented to set and get a dash list. This property will be deprecated and removed in the future, see {{bug(931643)}}. Use setLineDash() instead.webkitLineDash is implemented besides this method. Use setLineDash() instead.