This tutorial I will explain simple algorithm to draw polygons using HTML5 canvas API.

First we have to identify the points on HTML5 canvas and then use context.lineto() method for drawing lines and finally use stroke or fill method to make polygon visible. Here is the sample code for Drawing *HTML5 Canvas Polygon*

Html5 canvas API comes with so many options and we can draw anything using *Javascript,** * based upon path abstractions.

var c2 = canvas.getContext('2d'); c2.fillStyle = '#f00'; c2.beginPath(); c2.moveTo(0, 0); c2.lineTo(100,50); c2.lineTo(50, 100); c2.lineTo(0, 90); c2.closePath(); c2.fill();

But the problem is how identify the points to draw polygon?

In this post I will explain **how to draw a regular polygon using HTML5 Canvas. **

And also pattern to identify the points to draw polygon.

What exactly this regular polygon is.In a regular polygon all angles and all sides are equal.

If we observe the above images we can come to know that all vertices of regular polygon can be located on a circle.In other words regular polygon can be inscribed within a circle.

Also read: How to develop simple snake game using HTML5 cavas

We will go to our school days and understands some trigonometry functions cosine sine etc. Any point in a circle can be identified as (r cos e,r sin e) where r is the radius and e is the angle.Refer below images. This is the key point in our algorithm to draw regular * HTML5 Canvas Polygon.*

For instance we will take equilateral triangle,as explained above this triangle divides circle into three equal parts and each part will make an angle of 120 degrees at the center(360/3=120).

Now identify the three vertices

- First vertex : at 0 degree i.e., (r cos 0,r sin 0)=(r,0)
- Second vertx : at 120 degree i.e., (r cos 120,r sin 120)
- Third vertex : at 240 degree i.e., (r cos 240,r sin 240)

Now our algorithm is ready.

- First take number of sides(n) and radius of circle(r)
- And calculate angle made by the each side of regular polygon at center (360/n)
- Identify the first vertex (r,0)
- Loop through the angles to identify the points
- And draw the polygon using store or fill method

Observe the below code carefully I will explain each line one by one.

function regularpolygon(ctx, x, y, radius, sides) { if (sides < 3) return; ctx.beginPath(); var a = ((Math.PI * 2)/sides); ctx.translate(x,y); ctx.moveTo(radius,0); for (var i = 1; i < sides; i++) { ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i)); } ctx.closePath(); }

We are passing context(ctx),center of regular polygon(x,y),radius(r),number of sides(sides) as parameter to regular polygon function.if sides < 3 we cannot make a polygon so return directly.

Next angle calculation,HTML5 canvas and Javascript trigonometric functions will take radian as unit to specify angles rather than degrees.And 2*,Math.PI(Javascript notation for PI) is equal to 360 degrees.

Now moving the center to (x,y) using translate method.

Next We will move to the first point of regular polygon using moveTo() method that is nothing but (r,0) as explained above.

Loop through the sides to identify remaining two points and then close the path using closePath() .

*Draw Triangle using HTML5 Canvas:-*

*Draw Triangle using HTML5 Canvas:-*

However this function will not draw anything just it will define drawing path and we have to use storke or fill method to make polygon visible. Here is the sample HTML5 Code.

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script> $(document).ready(function(){ var canvas = $("#canvas")[0]; var context = canvas.getContext("2d"); polygon(context, 120,120,100,3); context.stroke(); }) function polygon(ctx, x, y, radius, sides) { if (sides < 3) return; var a = ((Math.PI * 2)/sides); ctx.beginPath();; ctx.translate(x,y); ctx.moveTo(radius,0); for (var i = 1; i < sides; i++) { ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i)); } ctx.closePath(); } </script> </head> <body> <canvas id="canvas" width="500" height="300">OOPS.. Upgrade your Browser</canvas> </body> </html>

This will draw the triangle exactly as shown in above figure (with radius (3,0)) But that is not visually straight because we made first point as (3,0)

To make triangle straight we have to rotate the context about 90 degrees(negative direction i.e., -Math.PI/2) so we will slightly change our method as shown below

function polygon(ctx, x, y, radius, sides, rotateAngle) { if (sides < 3) return; var a = (Math.PI * 2)/sides; ctx.beginPath(); ctx.translate(x,y); ctx.rotate(rotateAngle); ctx.moveTo(radius,0); for (var i = 1; i < sides; i++) { ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i)); } ctx.closePath(); }

And now below code will draw exactly straight triangle

polygon(context, 120,120,100,3,-Math.PI/2); context.stroke()

If you don’t want to rotate the triangle do not pass the last argument i.e., rotateAngle.

I hope you understand *how to draw a regular polygon using HTML5 canvas*.

But how we can generalize these to any polygon simply follow the below steps.For instance a take pentagon which is not regular pentagon

- Identify any five points on a circle.
- To identify the points we have to divide 360 degrees into 5 parts which are not equal(Say 80,90,100,30,60 degrees)
- These angles are nothing but angles made by the each side at center of circle.
- Now we know the points draw the lines using LineTo and finally stroke it. Please look into the below code.

*Draw Polygon using HTML5 Canvas:-*

*Draw Polygon using HTML5 Canvas:-*

var c = canvas.getContext("2d"); c.beginPath(); c.translate(120,120); c.moveTo(100,0); c.lineTo(100*Math.cos((Math.PI/180)*80),100*Math.sin((Math.PI/180)*80)); c.lineTo(100*Math.cos((Math.PI/180)*(80+90)),100*Math.sin((Math.PI/180)*(80+90))); c.lineTo(100*Math.cos((Math.PI/180)*(80+90+100)),100*Math.sin((Math.PI/180)*(80+90+100))); c.lineTo(100*Math.cos((Math.PI/180)*(80+90+100+30)),100*Math.sin((Math.PI/180)*(80+90+100+30))); c.closePath(); c.stroke();

For regular polygons all angles are equal so we took a for loop to identify the points but this is not the case for normal polygon so we have to add angles one by one to identify the points.

The above code looks somewhat tricky, But I feel this is the best way to identify the points of a polygon on HTML5 Canvas instead of giving points normally like c.lineTo(120,50) where we have to guess so many points to *Draw HTML5 Canvas Polygon*.

Live Demo For HTML5 Canvas Polygon

I hope you’ve enjoyed this article and that it gives you more ideas on how you can use the HTML5 Canvas API.

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook or googlePlus or linkedn to get in touch me. or join our mailing list

Great post , it told me what I wanted to know in an understandable way. The bit about the interrelationship of polygons to a circle is a very valuable thing to know, so thanks for explaining that