Name

addPt( ) — add a vertex to a polygon object

Synopsis

GD::Polygon::addPt(x, y)

This method adds a new vertex to a polygon object. Polygons must have at least three points and must be constructed one point at a time.

The GD::Polygonobject stores all of the points in the polygon, but it is also often useful to store the points separately as a string of coordinate pairs separated by whitespace. This format is easily written to or read from a file, and it is also consistent with the syntax that many web servers use to implement image maps. It is also a more concise and flexible way of constructing polygons than stringing together long series of addPt( ) method calls. It is simple to extract the points and construct a polygon from the string:

# Create a new polygon object
#
my $polywolly = new GD::Polygon;

# Store the vertices of the polygon in a string consisting of 
# x, y coordinate pairs separated by an arbitrary amount of whitespace
#
my $polyPoints = "0,0 10,10 30,10 20,0";

# The loop should iterate over each x,y pair
#
foreach (split /\s+/, $polyPoints) {
    $polywolly->addPt(split /,/, $_); # Split each pair into a two-value list
}

# Now draw the polygon in a (previously allocated) red color
#
$image->polygon($polywolly,$red);

Of course, in some cases, you will be creating a polygon dynamically, and won’t necessarily know all of the vertices at once. It still may be valuable to have a portable string representation of the polygon after the fact. See the vertices( ) method description ...

Get Programming Web Graphics with Perl and GNU Softwar now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.