crowyn has asked for the wisdom of the Perl Monks concerning the following question:

I am trying use GD module to draw some different polygons(equal side lenghth). It will be nice if I know the coordinates of each vertex to draw it in a given size of image. Otherwise, I have to use addPt function after calculate the the corresponding vertex coordinates. It will be pain if I want draw a polygon with 14 sides.
  • Comment on how to calculate polygon vertex coordinates

Replies are listed 'Best First'.
Re: how to calculate polygon vertex coordinates
by kvale (Monsignor) on Feb 13, 2004 at 16:40 UTC
    The general formula for vertices of a regular polygon in polar coordintates is
    (r,w_i) = (r, offset+2*pi*i/n), where i = 0, 1, ..., n-1
    with r the radius and offset the orientation. This polygon will fit inside a circle of radius r, or a 2r by 2r square.

    In rectangular coords, that is

    x_i = r * cos(w_i) y_i = r * sin(w_i)

    -Mark

      Thanks so much. It is really helpful.
Re: how to calculate polygon vertex coordinates
by bakunin (Scribe) on Feb 13, 2004 at 16:49 UTC
    Hi!
    I'm copying right from my SWF module with some changes; you will have to do some analyzing and reformating.
    It draws a polygon, given radius and number of sides. No GD by the way, but the algorithm should be applicable elsewhere.

    AGAIN: Just to illustrate one way to draw a polygon. The code below will not run!!
    sub polygon { my $r = shift; my $sides = shift; #Angles: my $theta = &rad(360/$sides); my $theta_half = &rad(180/$sides); #my $phase = &rad(0) ; my $beta = &rad ( (180-360/$sides) /2 ) ; my $s = $r * sin($theta)/sin($beta); my( $beginX,$beginY) = @M; my($sX,$sY); #Drawing: for ( 1..$sides ) { $sX = $s * cos(($_* $theta + $theta_half )); $sY = $s * sin(($_* $theta + $theta_half )); $shapeSWF->drawLineTo($beginX+$sX,$beginY+$sY); $beginX = $beginX+$sX; $beginY = $beginY+$sY; } }