Drawing regular polygons in javascript canvas

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:
  1. // hexagon
  2. var numberOfSides = 6,
  3.     size = 20,
  4.     Xcenter = 25,
  5.     Ycenter = 25;
  6.  
  7. cxt.beginPath();
  8. cxt.moveTo (Xcenter +  size * Math.cos(0), Ycenter +  size *  Math.sin(0));          
  9.  
  10. for (var i = 1; i <= numberOfSides;i += 1) {
  11.     cxt.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
  12. }
  13.  
  14. cxt.strokeStyle = "#000000";
  15. cxt.lineWidth = 1;
  16. cxt.stroke();
  17.  

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: