A while ago I wrote on this blog about how to draw polygons in Actionscript, by clicking on the stage and adding points dynamically. As I said in my last post, the blog was hacked and I decided to start fresh.

Today I am showing a little application that allows the user to draw regular polygons. The user can change most of the parameters of the polygons, such as number of sides, color, stroke, etc. To allow those changes, the polygons are created using a simple formula.

From the image above is clear that to make a triangle starting from a center point, one needs to put a point P0 at x = center.x and y = center.y – radius. Then, draw a line to the next point P1, which should be at (in Actionscript):

P1.x = radius * Math.sin((180 - 360*1/3)*RADTOANGLES); P1.y = radius * Math.cos((180 - 360*1/3)*RADTOANGLES);

Then, draw another line from P1 to P2 (the last Point), where the position of P2 is:

P2.x = radius * Math.sin((180 - 360*2/3)*RADTOANGLES); P2.y = radius * Math.cos((180 - 360*2/3)*RADTOANGLES);

And finally, draw another line form P2 to P0 to close the polygon. As you can see from the images above, the formula can be generalized to any regular polygon as:

Pi.x = radius * Math.sin((180 - 360*i/n + _initRot)*RADTOANGLES); Pi.y = radius * Math.cos((180 - 360*i/n + _initRot)*RADTOANGLES);

Where i is the point number, n is the number of sides on the Polygon. I included a variable _initRot in case you want to position the initial point at some angle other than 0.

The example below is done in Flash Builder (Flex), but it should be simple enough to implement the same formula in JavaScript or any other language.

Click **HERE** if you want to try it in full size (not constrained to the space provided in the blog).

In a future post, I will show how to extend the formulas to enable creating stars and bursts in addition to regular polygons.