To add a dotted stroke in the JavaScript canvas, we call the setLineDash
method.
For instance, we write
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.setLineDash([5, 10]);
ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "green";
ctx.moveTo(0, 75);
ctx.lineTo(250, 75);
ctx.stroke();
to call setLineDash
with the dash stroke lengths.
Then we call beginPath
to start drawing.
We set the line width by setting lineWidth
.
We set the stroke color by setting strokeStyle
.
Then we draw by calling moveTo
with the start point.
We call lineTo
to draw to the end point.
And we call stroke
to stop drawing.