How to draw polygons on an HTML5 canvas with JavaScript?

Spread the love

Sometimes, we want to draw polygons on an HTML5 canvas with JavaScript.

In this article, we’ll look at how to draw polygons on an HTML5 canvas with JavaScript.

How to draw polygons on an HTML5 canvas with JavaScript?

To draw polygons on an HTML5 canvas with JavaScript, we use the moveTo and lineTo methods.

For instance, we write

const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 50);
ctx.lineTo(50, 100);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fill();

to get the canvas context with getContext.

Then we set its fill color to red.

Next, we call beginPath to start drawing.

We call moveTo to move toi the coordinates to start drawing from.

We use lineTo to add a line to the given coordinates.

And then we call closePath to close the path of the polygon.

Finally we call fill to apply the fill color.

Conclusion

To draw polygons on an HTML5 canvas with JavaScript, we use the moveTo and lineTo methods.

Leave a Reply

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