# Drawing Regular Polygons in HTML5 canvas

March 3, 2011

Most of the drawing API’s available today doesn’t provide in-built support for drawing primitives like Triangle,Pentagon,Hexagon and etc. They leave that for developers creativity to generate them by using what is provided in the API. HTML5 canvas too doesn’t have anything readymade to draw polygons. But it is much easy to create one if we took our trigonometry classes serious. Well, I never understood the applied trigonometry myself either, until I started developing applications. Don’t panic, I’m not going to bore you with Mathematics or its tiresome equations and theories. To put it in a easily understandable language, all the regular polygons can be drawn with the use of circles (if we know the circumcircle  radius). For example, if are trying to draw a pentagon then draw an imaginary circle, divide its circumference at every 72 degrees (ie 360 / 5) and connect the divided points with lines finally you’ll have a pentagon. The Illustration is shown below,

Step 2

Let’s start putting that in a javascript function say ‘drawPolygon’

```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 function drawPolygon(x,y,radius,numOfSides) { var angChange = deg2rad(360.0/numOfSides); var prevX; var prevY; var firstX; var firstY; context.strokeStyle = '#0000FF'; context.lineWidth = 3; for(var i=0;i<numofsides;i++) { angle=i*angChange; prevX=x1; prevY=y1; x1=x+Math.cos(angle); var y1=y+Math.sin(angle) * radius; if(i> 0) { context.moveTo(prevX,prevY); context.lineTo(x1,y1); } else { firstX = x1; firstY = y1; } if(i == numOfSides-1) context.lineTo(firstX,firstY); context.stroke(); } }   function deg2rad(ang) { return ang * (Math.PI/180.0); }```

The drawPolygon() function takes the center point of the polygon (x,y), radius and number of sides in the polygon as a parameter and does a simple math of calculating the points on the invisible circle by dividing the circumference at equal distances. The for loop from line #9 through 26, calculates the point by incrementing the angle in each iteration. In the first iteration, the angle is 0 degree and hence the first point on the circle is at 0th degree. The angle system in HTML5 canvas works 3’o clock counter clockwise. So the first point is at 3’o clock position. As it iterates, the angle increases by 360/numOfSides calculating the other points. line 16 & 17 draws the line connecting consecutive points. and line 24 connects the last point with first point completing the polygon. The ‘context’ variable available in the snippet is the 2d drawing context obtained from HTML5 canvas.

```1 2 3 4 5 // Get the canvas 2d drawing context var context = document.getElementById('myCanvas').getContext('2d');   // Calling drawPolygon to draw a hexagon drawPolygon(100,100,150,6);```

### Choose number of sides:

Your browser doesn’t support HTML5 Canvas!

1. Stefan - March 24, 2012 8:50 pm

Nice idea!
Is there any possibility to fill the polygon?

Best regards.

2. Paramu - May 11, 2012 10:47 am

I insert Fill color… How to insert image in polygon ?

3. Paramu - May 11, 2012 3:43 pm

This is my code.. Pls guide me.. how to insert images in polygon

var img=new Image()
function getData() {
return {
’3rd Floor’: {
color: “tile.jpg”,
points: [{
x: 211,
y: 58
}, {
x:183,
y: 25
}, {
x: 590,
y: 23
}, {
x: 563,
y: 58
}]
},
}
}
function drawTooltip(tooltip, x, y, text) {
tooltip.setText(text);
var maxRight = 530;
if(x > maxRight) {
x = maxRight;
}
tooltip.setPosition(x, y);
tooltip.show();
tooltip.getLayer().draw();
}

var stage = new Kinetic.Stage({
container: “container”,
width: 1500,
height:847
});
var shapesLayer = new Kinetic.Layer();
/*
* throttle the tooltip layer down a bit
* so that the tooltip doesn’t lag behind the
* mouse too much on redraw
*/
var tooltipLayer = new Kinetic.Layer({
throttle: 20
});

// build tooltip
var tooltip = new Kinetic.Text({
text: “”,
textFill: “white”,
fontFamily: “Calibri”,
fontSize: 12,
fill: “black”,
visible: false,
alpha: 0.75
});

// get areas data
var areas = getData();

// draw areas
for(var pubKey in areas) {( function() {
var key = pubKey;
var area = areas[key];
var points = area.points;

var shape = new Kinetic.Polygon({
points: points,
fill: area.color,
alpha: 0
});

shape.on(“mouseover”, function() {
this.setAlpha(0.5);
shapesLayer.draw();
});
shape.on(“mouseout”, function() {
this.setAlpha(0);
shapesLayer.draw();
tooltip.hide();
tooltipLayer.draw();
});
shape.on(“mousemove”, function() {
var mousePos = stage.getMousePosition();
var x = mousePos.x + 5;
var y = mousePos.y + 10;
drawTooltip(tooltip, x, y, key);
});