Draw hexagons, octagons and other regular polygons using SVG

files

A regular polygon has N nodes, and N edges of the same length and it has all kinds of other things you can read in that Wikipedia article. We are going to create a function that can draw such a polygon using the Perl SVG module.

Let's see the results:

Hexagon

Hexagon SVG

Octagon

Octagon SVG

Dodecagon

Dodecagon SVG

The Code

examples/svg_regular_polygon.pl

use strict;
use warnings;
use 5.010;

use SVG;
use Math::Trig qw(:pi);

say create();

sub create {
    my $svg = SVG->new(
        width  => 120,
        height => 120,
    );

    my $n = 9;       # number of nodes
    my $r = 50;      # radius
    my $sr = 0;      # starting degree in radians
    my $cx = 60;     # center x 
    my $cy = 60;     # center y
    my @x;
    my @y;
    for my $i (1 .. $n) {
        push @x, $cx + $r * sin($sr + ($i * pi2 / $n)); 
        push @y, $cy + $r * cos($sr + ($i * pi2 / $n));
    }
    my $lt = $svg->polygon(
        %{ $svg->get_path(
            x => \@x,
            y => \@y,
            -type   => 'polygon',
            -closed  => 'true'
        )},
        style => {
            'fill-opacity' => 1,
            'fill'         => '#FF0000',
            'stroke'       => '#999',
            'stroke-width' => 1,
        },
    );

    return $svg->xmlify;
}


Between every two nodes of the N-sided regular polygon we have the exact same angle. Specifically 360/N in degrees or 2 * PI / N in radian.

We need to calculate these points and then draw a polygon with them.

The sin and cos functions that come with perl accept radian values and the Math::Trig module provides that via

#pi2 * 30 / 360; # apparently pi2 is the double of pi, the same as 2*pi)

Author

Gabor Szabo (szabgab) Gabor Szabo