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)
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 # 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(20, 100, 240, 20, 240, 180) canvas.setFill("white") canvas.drawPolygon(480, 100, 260, 20, 260, 180) # Wait for the user to close the window. win.wait() The drawing that results is shown below |
|||
Last modified: April 17, 2021, at 01:40 PM.
|