Categories
JavaScript Answers

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 call the lineTo method.

For instance, we write

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

to call getContext to return the canvas context.

Then we set the fill color with

ctx.fillStyle = "#f00";

Then we call moveTo to move to the first point of the polygon.

Next, we call lineTo to draw lines to the point in the argument from the previous point.

Then we call closePath to close the polygon.

Finally, we call fill to fill the polygon with the fillStyle color.

Conclusion

To draw polygons on an HTML5 canvas with JavaScript, we call the lineTo method.

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 *