Sometimes, we want to draw a dotted line in the HTML Canvas with JavaScript.
In this article, we’ll look at how to draw a dotted line in the HTML Canvas with JavaScript.
Draw a Dotted Line in the HTML Canvas with JavaScript
To draw a dotted line in the HTML Canvas with JavaScript, we can use the setLineDash
or mozDash
method.
For instance, we write:
<canvas width='200' height='200'></canvas>
to create the canvas.
Then we write:
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
if (ctx.setLineDash !== undefined) {
ctx.setLineDash([5, 10]);
}
if (ctx.mozDash !== undefined) {
ctx.mozDash = [5, 10];
}
ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "green";
ctx.moveTo(0, 75);
ctx.lineTo(250, 75);
ctx.stroke();
to get the canvas and its 2d context with:
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
Then we call setLineDash
or mozDash
to set the line style to a dashed line.
Next, we call beginPath
to start drawing.
Then we set the width and stroke styles with:
ctx.lineWidth = "2";
ctx.strokeStyle = "green";
Then we use moveTo
to move to the point where the line starts.
Then we use lineTo
to set the point where the line ends.
And finally, we call stroke
to draw the line into the canvas.
Conclusion
To draw a dotted line in the HTML Canvas with JavaScript, we can use the setLineDash
or mozDash
method.