JavaScript Answers

How to add a dotted stroke in the JavaScript canvas?

Spread the love

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.lineWidth = "2";
ctx.strokeStyle = "green";
ctx.moveTo(0, 75);
ctx.lineTo(250, 75);

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *