Submitted by ams on Tue, 01/17/2012 - 10:01

Geometric shapes such as regular polygons are useful building blocks for drawing more complex elements within JavaScript canvas tags. The following block shows 3, 4, 5, 6, 7, 8, 9 and 10 sided regular polygons.

Drawing regular polygons can be done by choosing the position for the center of the polygon, moving to the perimeter and then drawing a series of lines using the Math.cos(), Math.sin() and Math.PI functions. In JavaScript, angles are measured in radians. There are 2*PI radians in a circle. The number of points to plot around the circle is 2*PI divided by the number of sides on the desired polygon.
The following code snippet will draw a hexagon:

// hexagon

var numberOfSides = 6,

size = 20,

Xcenter = 25,

Ycenter = 25;

cxt.beginPath();

cxt.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));

for (var i = 1; i <= numberOfSides;i += 1) {

cxt.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));

}

cxt.strokeStyle = "#000000";

cxt.lineWidth = 1;

cxt.stroke();

By changing the value of

`numberOfSides`

, any regular polygon can be drawn. Altering the value of

`size`

allows larger and smaller shapes to be drawn.

You might also like: