Canvas¶
A drawing area for 2D vector graphics.






Not supported
Not supported
Seeing deprecation warnings?
If you've updated Toga from 0.5.3 to 0.5.4 or newer and are seeing deprecation warnings from your existing code that uses Canvas, check the migration guide for info on how to update to the new API.
Usage¶
Canvas is a 2D vector graphics drawing area, whose API broadly follows the HTML5 Canvas API. Drawing methods are called directly on the Canvas. All positions and sizes are measured in CSS pixels.
For example, the following code will draw an orange horizontal line:
import toga
canvas = toga.Canvas()
canvas.stroke_style = "orange"
canvas.begin_path()
canvas.move_to(20, 20)
canvas.line_to(160, 20)
canvas.stroke()
Result:

Additional features¶
Toga adds some additional Pythonic conveniences to the base HTML5 API. First, a number of drawing methods that have a natural open/close life cycle (close_path(), stroke(), and fill()) can additionally function as context managers. Second, fill and stroke accept optional arguments to specify their parameters directly. Using both of these features, the previous example could be rewritten to:
import toga
canvas = toga.Canvas()
with canvas.stroke(stroke_style="orange"):
canvas.move_to(20, 20)
canvas.line_to(160, 20)
Toga also provides one additional method, state(), which is useful only as a context manager; it saves context upon entering, and restores it upon existing. That is, the two following snippets are functionally identical:
canvas.fill_style = "blue"
canvas.save()
canvas.fill_style = "red"
canvas.restore()
# Fill style is now restored to blue.
canvas.fill_style = "blue"
with canvas.state():
canvas.fill_style = "red"
# Fill style is now restored to blue.
Further reading¶
This page documents all of Canvas's drawing methods; for more detailed and illustrative tutorials, see the MDN documentation for the HTML5 Canvas API. Other than the change in naming conventions for methods - the HTML5 API uses lowerCamelCase, whereas the Toga API uses snake_case - both APIs are very similar.
Notes¶
-
Toga does not guarantee pixel perfect rendering of Canvas content across all platforms. Most drawing instructions will appear identical across all platforms, and in the worst case, any given set of drawing instructions should result in a fundamentally similar image. However, text and other complex curve and line geometries (such as miters on tight corners) will result in minor discrepancies between platforms. Color rendition can also vary slightly between platforms depending on the color profiles of the device being used to render the canvas.
-
The Canvas API allows the use of handlers to respond to mouse/pointer events. These event handlers differentiate between "primary" and "alternate" modes of activation. When a mouse is in use, alternate activation will usually be interpreted as a "right click"; however, platforms may not implement an alternate activation mode. To ensure cross-platform compatibility, applications should not use the alternate press handlers as the sole mechanism for accessing critical functionality.
Advanced usage¶
It's also possible to reach beyond the HTML Canvas-based API documented here, and interact directly with the underlying structure that Canvas uses to store the series of drawing operations it's performed. This allows you to modify the rendered result non-linearly, going "back in time" to change previous instructions. For more information, see the documentation for DrawingAction.
Reference¶
toga.Canvas
¶
Canvas(
id: str | None = None,
style: StyleT | None = None,
on_resize: OnResizeHandler | None = None,
on_press: OnTouchHandler | None = None,
on_activate: OnTouchHandler | None = None,
on_release: OnTouchHandler | None = None,
on_drag: OnTouchHandler | None = None,
on_alt_press: OnTouchHandler | None = None,
on_alt_release: OnTouchHandler | None = None,
on_alt_drag: OnTouchHandler | None = None,
**kwargs,
)
Bases: Widget, DrawingActionDispatch
Create a new Canvas widget.
Inherits from toga.Widget.
| PARAMETER | DESCRIPTION |
|---|---|
id
|
The ID for the widget.
TYPE:
|
style
|
A style object. If no style is provided, a default style will be applied to the widget.
TYPE:
|
on_resize
|
Initial
TYPE:
|
on_press
|
Initial
TYPE:
|
on_activate
|
Initial
TYPE:
|
on_release
|
Initial
TYPE:
|
on_drag
|
Initial
TYPE:
|
on_alt_press
|
Initial
TYPE:
|
on_alt_release
|
Initial
TYPE:
|
on_alt_drag
|
Initial
TYPE:
|
kwargs
|
Initial style properties.
DEFAULT:
|
line_dash
class-attribute
instance-attribute
¶
The current dash pattern to follow when drawing the line, expressed as alternating lengths of dashes and spaces. The default is a solid line.
In the HTML Canvas API, this has to be set via setLineDash(). Here it's directly assignable.
enabled
property
writable
¶
enabled: Literal[True]
Is the widget currently enabled? i.e., can the user interact with the widget? Canvas widgets cannot be disabled; this property will always return True; any attempt to modify it will be ignored.
on_activate
property
writable
¶
on_activate: OnTouchHandler
The handler invoked when the canvas is pressed in a way indicating the pressed object should be activated. When a mouse is in use, this will usually be a double click with the primary (usually the left) mouse button.
This event is not supported on Android or iOS.
on_alt_drag
property
writable
¶
on_alt_drag: OnTouchHandler
The handler to invoke when the location of an alternate press changes.
This event is not supported on Android or iOS.
on_alt_press
property
writable
¶
on_alt_press: OnTouchHandler
The handler to invoke when the canvas is pressed in an alternate manner. This will usually correspond to a secondary (usually the right) mouse button press.
This event is not supported on Android or iOS.
on_alt_release
property
writable
¶
on_alt_release: OnTouchHandler
The handler to invoke when an alternate press is released.
This event is not supported on Android or iOS.
on_drag
property
writable
¶
on_drag: OnTouchHandler
The handler invoked when the location of a press changes.
on_press
property
writable
¶
on_press: OnTouchHandler
The handler invoked when the canvas is pressed. When a mouse is being used, this press will be with the primary (usually the left) mouse button.
on_release
property
writable
¶
on_release: OnTouchHandler
The handler invoked when a press on the canvas ends.
on_resize
property
writable
¶
on_resize: OnResizeHandler
The handler to invoke when the canvas is resized.
save
¶
save() -> Save
Save the current state of the drawing context.
| RETURNS | DESCRIPTION |
|---|---|
Save
|
The |
restore
¶
restore() -> Save
Restore to the previous state of the drawing context.
| RETURNS | DESCRIPTION |
|---|---|
Save
|
The |
state
¶
state() -> AbstractContextManager[State]
A context manager that saves the current state of the Canvas context, and restores it upon exiting.
| RETURNS | DESCRIPTION |
|---|---|
AbstractContextManager[State]
|
Yields the new |
begin_path
¶
begin_path() -> BeginPath
Start a new path.
| RETURNS | DESCRIPTION |
|---|---|
BeginPath
|
The |
close_path
¶
close_path() -> AbstractContextManager[ClosePath]
Close the current path.
This closes the current path as a simple drawing operation. It should be paired
with a begin_path() operation, or else used as a
context manager. If used as a context manager, it begins a path when entering,
and closes it upon exiting.
| RETURNS | DESCRIPTION |
|---|---|
AbstractContextManager[ClosePath]
|
The |
move_to
¶
Moves the current point without drawing.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The x coordinate of the new current point.
TYPE:
|
y
|
The y coordinate of the new current point.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MoveTo
|
The |
line_to
¶
Draw a line segment ending at a point.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The x coordinate for the end point of the line segment.
TYPE:
|
y
|
The y coordinate for the end point of the line segment.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LineTo
|
The |
bezier_curve_to
¶
bezier_curve_to(
cp1x: float, cp1y: float, cp2x: float, cp2y: float, x: float, y: float
) -> BezierCurveTo
Draw a Bézier curve.
A Bézier curve requires three points. The first two are control points; the
third is the end point for the curve. The starting point is the last point in
the current path, which can be changed using move_to() before creating the
Bézier curve.
| PARAMETER | DESCRIPTION |
|---|---|
cp1y
|
The y coordinate for the first control point of the Bézier curve.
TYPE:
|
cp1x
|
The x coordinate for the first control point of the Bézier curve.
TYPE:
|
cp2x
|
The x coordinate for the second control point of the Bézier curve.
TYPE:
|
cp2y
|
The y coordinate for the second control point of the Bézier curve.
TYPE:
|
x
|
The x coordinate for the end point.
TYPE:
|
y
|
The y coordinate for the end point.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BezierCurveTo
|
The |
quadratic_curve_to
¶
quadratic_curve_to(
cpx: float, cpy: float, x: float, y: float
) -> QuadraticCurveTo
Draw a quadratic curve.
A quadratic curve requires two points. The first point is a control point; the
second is the end point. The starting point of the curve is the last point in
the current path, which can be changed using moveTo() before creating the
quadratic curve.
| PARAMETER | DESCRIPTION |
|---|---|
cpx
|
The x axis of the coordinate for the control point of the quadratic curve.
TYPE:
|
cpy
|
The y axis of the coordinate for the control point of the quadratic curve.
TYPE:
|
x
|
The x axis of the coordinate for the end point.
TYPE:
|
y
|
The y axis of the coordinate for the end point.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
QuadraticCurveTo
|
The |
arc
¶
arc(
x: float,
y: float,
radius: float,
startangle: float = 0.0,
endangle: float = 2 * pi,
counterclockwise: bool | None = None,
anticlockwise: bool | None = None,
) -> Arc
Draw a circular arc.
A full circle will be drawn by default; an arc can be drawn by specifying a start and end angle.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The X coordinate of the circle's center.
TYPE:
|
y
|
The Y coordinate of the circle's center.
TYPE:
|
startangle
|
The start angle in radians, measured clockwise from the positive X axis.
TYPE:
|
endangle
|
The end angle in radians, measured clockwise from the positive X axis. |
counterclockwise
|
If true, the arc is swept counterclockwise. The default is clockwise.
TYPE:
|
anticlockwise
|
DEPRECATED - Use
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Arc
|
The |
ellipse
¶
ellipse(
x: float,
y: float,
radiusx: float,
radiusy: float,
rotation: float = 0.0,
startangle: float = 0.0,
endangle: float = 2 * pi,
counterclockwise: bool | None = None,
anticlockwise: bool | None = None,
) -> Ellipse
Draw an elliptical arc.
A full ellipse will be drawn by default; an arc can be drawn by specifying a start and end angle.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The X coordinate of the ellipse's center.
TYPE:
|
y
|
The Y coordinate of the ellipse's center.
TYPE:
|
radiusx
|
The ellipse's horizontal axis radius.
TYPE:
|
radiusy
|
The ellipse's vertical axis radius.
TYPE:
|
rotation
|
The ellipse's rotation in radians, measured clockwise around its center.
TYPE:
|
startangle
|
The start angle in radians, measured clockwise from the positive X axis.
TYPE:
|
endangle
|
The end angle in radians, measured clockwise from the positive X axis. |
counterclockwise
|
If true, the arc is swept counterclockwise. The default is clockwise.
TYPE:
|
anticlockwise
|
DEPRECATED - Use
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Ellipse
|
The |
rect
¶
Draw a rectangle.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The horizontal coordinate of the left of the rectangle.
TYPE:
|
y
|
The vertical coordinate of the top of the rectangle.
TYPE:
|
width
|
The width of the rectangle.
TYPE:
|
height
|
The height of the rectangle.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Rect
|
The |
round_rect
¶
round_rect(
x: float,
y: float,
width: float,
height: float,
radii: float | CornerRadiusT | Iterable[float | CornerRadiusT],
) -> RoundRect
Draw a rounded rectangle.
Corner radii can be provided as: - a single numerical radius for both x and y radius for all corners - an object with attributes "x" and "y" for the x and y radius for all corners - a list of 1 to 4 of the above
If the list has: - length 1, then the item gives the radius of all corners - length 2, then the upper left and lower right corners use the first radius, and upper right and lower left use the second radius - length 3, then the upper left corner uses the first radius, the upper right and lower left use the second radius, and the lower right corner uses the third radius - length 4, then the radii are given in order upper left, upper right, lower left, lower right
If the radii are too large for the width or height, then they will be scaled.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The horizontal coordinate of the left of the rounded rectangle.
TYPE:
|
y
|
The vertical coordinate of the top of the rounded rectangle.
TYPE:
|
width
|
The width of the rounded rectangle.
TYPE:
|
height
|
The height of the roundedrectangle.
TYPE:
|
radii
|
The corner radii of the rounded rectangle.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RoundRect
|
The |
fill
¶
fill(
fill_rule: FillRule = NONZERO,
*,
fill_style: ColorT | None | object = NOT_PROVIDED,
color: ColorT | None | object = NOT_PROVIDED,
) -> AbstractContextManager[Fill]
Fill the current path.
The fill can use either the Non-Zero or Even-Odd winding rule for filling paths.
If used as a context manager, this begins a new path, and moves to the specified
(x, y) coordinates (if both are specified). When the context is exited, the
path is filled.
| PARAMETER | DESCRIPTION |
|---|---|
fill_rule
|
|
fill_style
|
The fill style. At present, only accepts colors; gradients and patterns are not supported. |
color
|
Alias for fill_style. |
| RETURNS | DESCRIPTION |
|---|---|
AbstractContextManager[Fill]
|
The |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If both |
stroke
¶
stroke(
*,
stroke_style: ColorT | None | object = NOT_PROVIDED,
color: ColorT | None | object = NOT_PROVIDED,
line_width: float | None = None,
line_dash: list[float] | None = None,
) -> AbstractContextManager[Stroke]
Draw the current path as a stroke.
If used as a context manager, this begins a new path, and moves to the specified
(x, y) coordinates (if both are specified). When the context is exited, the
path is stroked.
| PARAMETER | DESCRIPTION |
|---|---|
stroke_style
|
The stroke style. At present, only accepts colors; gradients and patterns are not supported. |
color
|
Alias for fill_style. |
line_width
|
The width of the stroke.
TYPE:
|
line_dash
|
The dash pattern to follow when drawing the line, expressed as alternating lengths of dashes and spaces. The default is a solid line. |
| RETURNS | DESCRIPTION |
|---|---|
AbstractContextManager[Stroke]
|
The |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If both |
write_text
¶
write_text(
text: str,
x: float = 0.0,
y: float = 0.0,
font: Font | None = None,
baseline: Baseline = ALPHABETIC,
line_height: float | None = None,
) -> WriteText
Write text at a given position.
Unlike HTML canvas's fill_text and stroke_text, Toga currently has one
method; whether it strokes and/or fills is determined by whether a stroke
and/or fill context manager is currently open.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
The text to draw. Newlines will cause line breaks, but long lines will not be wrapped.
TYPE:
|
x
|
The X coordinate of the text's left edge.
TYPE:
|
y
|
The Y coordinate: its meaning depends on
TYPE:
|
font
|
The font in which to draw the text. The default is the system font.
TYPE:
|
baseline
|
Alignment of text relative to the Y coordinate.
TYPE:
|
line_height
|
Height of the line box as a multiple of the font size when multiple lines are present.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
WriteText
|
The |
draw_image
¶
draw_image(
image: Image,
x: float = 0.0,
y: float = 0.0,
width: float | None = None,
height: float | None = None,
)
Draw a Toga Image.
The x, y coordinates specify the location of the bottom-left corner of the image. If supplied, the width and height specify the size of the image when it is rendered; the image will be scaled to fit.
Drawing of images is performed with the current transformation matrix applied, so the destination rectangle of the image will be rotated, scaled and translated by any transformations which are currently applied.
| PARAMETER | DESCRIPTION |
|---|---|
image
|
a Toga Image
TYPE:
|
x
|
The x-coordinate of the bottom-left corner of the image when it is drawn.
TYPE:
|
y
|
The y-coordinate of the bottom-left corner of the image when it is drawn.
TYPE:
|
width
|
The width of the destination rectangle where the image will be drawn. The image will be scaled to fit the width. If the width is omitted, the natural width of the image will be used and no scaling will be done.
TYPE:
|
height
|
The height of the destination rectangle where the image will be drawn. The image will be scaled to fit the height. If the height is omitted, the natural height of the image will be used and no scaling will be done.
TYPE:
|
rotate
¶
Add a rotation.
| PARAMETER | DESCRIPTION |
|---|---|
radians
|
The angle to rotate clockwise in radians.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Rotate
|
The |
scale
¶
Add a scaling transformation.
| PARAMETER | DESCRIPTION |
|---|---|
sx
|
Scale factor for the X dimension. A negative value flips the image horizontally.
TYPE:
|
sy
|
Scale factor for the Y dimension. A negative value flips the image vertically.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Scale
|
The |
translate
¶
Add a translation.
| PARAMETER | DESCRIPTION |
|---|---|
tx
|
Translation for the X dimension.
TYPE:
|
ty
|
Translation for the Y dimension.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Translate
|
The |
reset_transform
¶
reset_transform() -> ResetTransform
Reset all transformations.
| RETURNS | DESCRIPTION |
|---|---|
ResetTransform
|
A |
measure_text
¶
measure_text(
text: str, font: Font | None = None, line_height: float | None = None
) -> tuple[float, float]
Measure the size at which
Canvas.write_text
would render some text.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
The text to measure. Newlines will cause line breaks, but long lines will not be wrapped.
TYPE:
|
font
|
The font in which to draw the text. The default is the system font.
TYPE:
|
line_height
|
Height of the line box as a multiple of the font size when multiple lines are present.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[float, float]
|
A tuple of |
as_image
¶
Render the canvas as an image.
| PARAMETER | DESCRIPTION |
|---|---|
format
|
Format to provide. Defaults to |
| RETURNS | DESCRIPTION |
|---|---|
ImageT
|
The canvas as an image of the specified type. |
redraw
¶
redraw() -> None
Redraw the Canvas. This shouldn't normally need to be manually called; for
more info, see
DrawingAction.
toga.widgets.canvas.OnTouchHandler
¶
Bases: Protocol
__call__
¶
A handler that will be invoked when a Canvas is
touched with a finger or mouse.
| PARAMETER | DESCRIPTION |
|---|---|
widget
|
The canvas that was touched.
TYPE:
|
x
|
X coordinate, relative to the left edge of the canvas.
TYPE:
|
y
|
Y coordinate, relative to the top edge of the canvas.
TYPE:
|
kwargs
|
Ensures compatibility with arguments added in future versions.
TYPE:
|