Paths
A path allows you to create a shape by connecting a series of points by lines or curves. The usual way to use paths involves:
Creating a
Path
instance (which also specifies its initial location)from scripton.canvas import Path, Canvas path = Path(x=30, y=20)Invoking a series of methods on the
Path
instance (likepath.line_to
orpath.arc_to
)path.line_to(x=270, y=180) path.move_to(x=30, y=180) path.line_to(x=270, y=20)Drawing it on a
Canvas
instance using itsdraw_path
methodcanvas = Canvas(width=300, height=200) canvas.draw_path(path, stroke='#D38EE7')
As shown above, creating a Path
instance and calling its various methods (like line_to
or ellipse
) doesn't result in any drawing. Instead, that occurs when the path is passed to a canvas instance's draw_path
method. The same path can be drawn multiple times.
Current Position
Most methods described below implicitly start at the current position. This refers to the last set position of the path. It starts off as the point specified at construction (eg: Path(x=30, y=20)
). Each subsequent path operation may alter this. For instance, path.line_to(x=270, y=20)
leaves the current position at (270, 20)
. You can always explicitly set the current position using move_to
.
API
Path.line_to
Adds a straight line from the current position to the newly specified one.
Path.move_to
You can "lift up the pen" and move to a new location for a sub-path using the move_to
method:
Path.arc_to
Adds an arc specified by the two control points ((x1, y1)
and (x2, y2)
) and a radius
.
Here's an annotated version of the same arc that provides some insights into how it's produced —
The precise details of how arc_to
behaves matches the HTML Canvas specifications.
Path.bezier_curve_to
Adds a cubic Bézier curve specified by two control points ((cp1x, cp1y)
and (cp2x, cp2y)
) and an end point ((epx, epy)
).
The following figure visualizes the parameters of the Bézier curve above.
Path.quadratic_curve_to
Adds a quadratic Bézier curve specified by a single control point ((cpx, cpy)
) and an end point ((epx, epy)
).
The following figure visualizes the parameters of the quadratic Bézier curve above.
Path.arc
Adds an arc centered at (x, y)
with a given radius
, and starting and ending angles measured in radians. An optional counterclockwise
keyword argument (False
by default) controls the direction in which the path is rendered.
Path.ellipse
Adds an elliptical arc specified by its center ((x, y)
), radii (radius_x
, radius_y
). Optional keyword-only arguments include:
rotation
angle for the ellipse (measured in radians)start_angle
andend_angle
for the arc (measured in radians)counterclockwise
(defaults toFalse
) for controlling the direction of the arc.
Path.close
Draws a straight-line from the current position to the start of the path. Calling close
on an already closed path (or one with fewer than two points) is effectively a no-op.
Path.clone
Returns a copy of the path. Updates to this copy leave the original path unaffected.