Polygons

Drawing Properties UserGuide Ovals and Circles

Simple polygons can be drawn on a canvas using using the drawPolygon() canvas method. A simple polygon is a closed shape with three or more vertices in which adjacent vertices are connected by straight line segments. A vertex is defined by the x- and y-coordinates of its position on the canvas.

To draw a polygon, you pass the collection of vertices that define the polygon to the method as a sequence of arguments

canvas.drawPolygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5)

in which the x- and y-coordinate pairs of each vertex are passed one after the other. Thus, the x- and y-coordinates of the first vertex are passed first, followed by the coordinates of the second vertex, and so on. For example, the command

canvas.drawPolygon(200, 100, 50, 200, 150, 300, 250, 300, 350, 200)
 

draws a 5 sided polygon on the canvas that is defined by the vertices (200, 100), (50, 200), (150, 300), (250, 300), (350, 200)

As an alternative, you can store the coordinates within a list or tuple and pass the structure to the method instead of the individual coordinates

canvas.drawPolygon(sequence)

The vertices must be stored within the list or tuple in the same order they would be passed to the method as a sequence of coordinates.

samplePoly = [200, 100, 50, 200, 150, 300, 250, 300, 350, 200]
canvas.drawPolygon(samplePoly)
 
WarningWarning

Since a polygon is defined by at least 3 vertices, you must pass at least 6 coordinates to the drawPolygon() method and the total number of coordinates must be an even number.

The following program draws two triangles on the canvas using lists to store the vertex coordinates.

Program: triangle.py
## triangle.py
#  -- Draws two triangles using lists for the coordinates.

from ezgraphics import GraphicsWindow

# Define the list of vertices for the triangles.
triangle1 = [20, 100, 240, 20, 240, 180]
triangle2 = [480, 100, 260, 20, 260, 180]

# Create the graphics window.
win = GraphicsWindow(500, 200)
win.setTitle("Triangles")

# Draw the triangles.
canvas = win.canvas()
canvas.setBackground("blue")

canvas.setFill("yellow")
canvas.drawPolygon(triangle1)

canvas.setFill("white")
canvas.drawPolygon(triangle2)

# Wait for the user to close the window.
win.wait()
 

The drawing that results is shown below



Drawing Properties UserGuide Ovals and Circles

Last modified: August 19, 2013, at 01:37 PM.