Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing Dashed lines on HTML5 Canvas?

Tags:

html

canvas

line

I would like to draw some dashed lines on HTML5 canvas. But I couldn't find there is such a feature. the canvas path could only draw solid lines. And people have tried to use some border feature (dotted, dashed) in CSS to draw dashed lines, but they could only be horizontal or vertical. So I got stuck on this. I also found a library called RGraph and it could draw dashed lines. But using an external library would make the drawing really slow. So does any body has an idea how to implement this? Any help will be appreciated.

like image 453
April Lee Avatar asked Mar 13 '13 21:03

April Lee


People also ask

How do I create a dotted line in HTML canvas?

To draw a dotted line in the HTML Canvas with JavaScript, we can use the setLineDash or mozDash method. to create the canvas. Then we call setLineDash or mozDash to set the line style to a dashed line. Next, we call beginPath to start drawing.

How do I draw a dotted line in canvas android?

setARGB(255, 0, 0, 0); dashPaint. setStyle(Paint. Style. STROKE); dashPaint.


2 Answers

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.setLineDash([5, 3]);/*dashes are 5px and spaces are 3px*/ ctx.beginPath(); ctx.moveTo(0,100); ctx.lineTo(400, 100); ctx.stroke(); 

JsFIDDLE

like image 61
Jignesh Variya Avatar answered Sep 24 '22 20:09

Jignesh Variya


This is an easier way to create dashed lines :

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

Hope that helps.

like image 36
API Avatar answered Sep 26 '22 20:09

API