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.
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.
setARGB(255, 0, 0, 0); dashPaint. setStyle(Paint. Style. STROKE); dashPaint.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With