Forum Archive

Can't fill path

heyguy4

Okay, so I'm trying to use the canvas to draw a trapezoid. Here's my code. For some reason it just creates an empty box.

```

coding: utf-8

import canvas
b = 10
canvas.set_size(500, 500 + b)
canvas.draw_rect(0, 0 + b, 500, 500)
canvas.set_fill_color(1, 0.1, 0.1)
canvas.set_stroke_color(1, 0, 0)
canvas.set_line_width(4)
canvas.begin_path()
canvas.add_line(150, 100 + b)
canvas.add_line(350, 100 + b)
canvas.add_line(400, 200 + b)
canvas.add_line(100, 200 + b)
canvas.add_line(150, 100 + b)
canvas.draw_path()
canvas.fill_path()
canvas.close_path()

dgelessus

A few things:

  • There are two sets of functions in the canvas module - there are the draw_something and fill_something functions, which draw shapes to the canvas immediately, and there are the add_something functions, which add drawings to a "path" that you can display with draw_path or fill_path.
  • When you call draw_path or fill_path, the path is drawn and then cleared. This means that when you call draw_path (creating the outline) it also gets cleared from memory, so when you call fill_path afterwards there is nothing there to fill.
  • close_path doesn't do what you think it does (probably). The way you use it, it looks like you think close_path is required to "finish" a path started with begin_path - this is not the case. What it does is connect the current "drawing point" of the path with the point where you started the path, making the line into a closed shape. For example, when you add lines to a path in an L shape and then call close_path, you connect the two ends of the L with a line and get a triangle.
  • I might be wrong, but it looks like when adding lines to a path you need to start with a move_to call to set the path's starting point. When I didn't call move_to, the lines I added were not drawn.
JonB

The canvas is also somewhat "depreciated" I think -- the ui or scene drawing functions are a little more complete. For instance, using a ui.Path, you could fill then stroke.

brumm

Example with ImageDraw:

import Image, ImageDraw
b = 10
imagebuffer = Image.new('RGBA', (501, 500 + b), 'white')
drawbuffer = ImageDraw.Draw(imagebuffer)

drawbuffer.rectangle((0, b, 500, 500), outline='red')

drawpoints = [(150, 100 + b), (350, 100 + b), (400, 200 + b), (100, 200 + b), (150, 100 + b)]
#drawbuffer.line(drawpoints, fill='red', width=4)
drawbuffer.polygon(drawpoints, fill='red')    #filled path

imagebuffer.show()