How to draw polygons on an HTML5 canvas with JavaScript?

Spread the love

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

For instance, we write

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

to get the canvas context with getContext.

And then we call beginPath to start drawing.

We call moveTo to move to the starting point.

Then we call lineTo to draw a line to the next point.

Next, we call closePath to close the path.

And we call fill to apply the fillStyle color as the fill color of the polygon.

Leave a Reply

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