N-sided shapes

You’ll probably know that the formula for calculating the interior angle of a regular polygon is 180(n – 2) / n where n is the number of sides:

Angle formula

So if we put 4 (i.e. a square) into the formula we 90 degrees, if we stick in 5 (pentagon) we get 108 degrees. Simple. In fact, lets create a JavaScript function to draw these shapes if we enter a starting coordinate, side length and number of sides:

 function drawShape(c, startX, startY, sideLength, sideCount)
 {
  var interiorAngleDegrees = (180 * (sideCount - 2)) / sideCount;
  var interiorAngle = Math.PI - Math.PI * interiorAngleDegrees / 180; //Convert to radians
  c.save();
  c.beginPath();
  c.translate(startX, startY);
  c.moveTo(0,0);
  for (var i = 0; i < sideCount; i++)
  {
    c.lineTo(sideLength,0);
    c.translate(sideLength,0);
    c.rotate(interiorAngle);
  }
  c.stroke();
  c.restore();
}
Example of a square

Example of a square drawn with function

Now, if what happens if we take our original formula and stick in something that isn’t an integer. If we put in 2.5 we get out 54 degrees. What does a 2.5 sided shape look like with the above function?

A '2.5' sided shape.

A ‘2.5’ sided shape.

Clearly this isn’t a full polygon, so perhaps it is better to think of 2.5 as 5/2. Let’s adapt the function a little:

function drawShape(c, startX, startY, sideLength, sideCountNumerator, sideCountDenominator)
 {
   var sideCount = sideCountNumerator * sideCountDenominator;
   var decimalSides = sideCountNumerator / sideCountDenominator;
   var interiorAngleDegrees = (180 * (decimalSides - 2)) / decimalSides;
   var interiorAngle = Math.PI - Math.PI * interiorAngleDegrees / 180; //Convert to radians
   c.save();
   c.beginPath();
   c.translate(startX, startY);
   c.moveTo(0,0);
   for (var i = 0; i < sideCount; i++)
   {
     c.lineTo(sideLength,0);
     c.translate(sideLength,0);
     c.rotate(interiorAngle);
   }
   c.stroke();
   c.restore();
 }

Now the function can draw 5 / 2 shapes:

A 5 / 2 sided regular polygon.

A 5 / 2 sided regular polygon.

If you want to check out a full source code example, you can see it here.

Advertisements

One thought on “N-sided shapes

  1. Pingback: Drawing stars with HTML5 Canvas | Programming Thomas

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s