Martin McBride, 2020-08-18
Tags geometry polygon
Categories generativepy generative art

The Polygon class draws a polygon.

There is also a polygon function that just creates a polygon as a new path.

Polygon class methods

The Polygon class inherits add, fill, stroke, and fill_stroke from Shape.

It has additional methods:

  • of_points
  • open


Creates a polygon based on a list of points.

Parameter Type Description
points list of (number, number) A sequence of (x, y) tuples, giving the position of each vertex of the polygon.

The polygon will be closed by default. To create an open polygon, call the open method.


Creates an open polygon, rather than a closed polygon.


Calling this method will cause the final polygon to be open - the last point will not be connected to the first point (see the example). To create a closed polygon, simply don't call this method.

polygon function

Adds a polygon as a new path, without the need to create a Polygon object in code.

polygon(ctx, points, closed=True)
Parameter Type Description
ctx Context The Pycairo Context to draw to
points list of (number, number) A sequence of (x, y) tuples, giving the position of each vertex of the polygon.
closed boolean Optional, set to False to create an open polygon


Here is some example code that draws polygons using the class and the utility function. The full code can be found on github.

from generativepy.drawing import make_image, setup
from generativepy.color import Color
from generativepy.geometry import polygon, Polygon

Create polygons using the geometry module.

def draw(ctx, width, height, frame_no, frame_count):
    setup(ctx, width, height, width=500, background=Color(0.8))

    # The polygon function is a convenience function that adds a polygon as a new path.
    # You can fill or stroke it as you wish.
    polygon(ctx, ((100, 100), (150, 50), (200, 150), (200, 200)))
    ctx.set_source_rgba(*Color(1, 0, 0))

    Polygon(ctx).of_points([(300, 100), (300, 150), (400, 200), (450, 100)]).open().stroke(Color('orange'), 10)

make_image("/tmp/geometry-polygon.png", draw, 500, 500)

Copyright (c) Axlesoft Ltd 2020