Canvas¶
A drawing area for 2D vector graphics.





Not supported
Not supported
Usage¶
Canvas is a 2D vector graphics drawing area, whose API broadly follows the HTML5 Canvas API. The Canvas provides a drawing Context; drawing instructions are then added to that context by calling methods on the context. 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()
context = canvas.context
context.begin_path()
context.move_to(20, 20)
context.line_to(160, 20)
context.stroke(color="orange")
Toga adds an additional layer of convenience to the base HTML5 API by providing context managers for operations that have a natural open/close life cycle. For example, the previous example could be replaced with:
import toga
canvas = toga.Canvas()
with canvas.context.Stroke(20, 20, color="orange") as stroke:
stroke.line_to(160, 20)
Any argument provided to a drawing operation or context object becomes a property of that object. Those properties can be modified after creation, after which you should invoke Canvas.redraw to request a redraw of the canvas.
Drawing operations can also be added to or removed from a context using the list operations append, insert, remove and clear. In this case, Canvas.redraw will be called automatically.
For example, if you were drawing a bar chart where the height of the bars changed over time, you don't need to completely reset the canvas and redraw all the objects; you can use the same objects, only modifying the height of existing bars, or adding and removing bars as required.
In this example, we create 2 filled drawing objects, then manipulate those objects, requesting a redraw after each set of changes.
import toga
canvas = toga.Canvas()
with canvas.context.Fill(color="red") as fill:
circle = fill.arc(x=50, y=50, radius=15)
rect = fill.rect(x=50, y=50, width=15, height=15)
# We can then change the properties of the drawing objects.
# Make the circle smaller, and move it closer to the origin.
circle.x = 25
circle.y = 25
circle.radius = 5
canvas.redraw()
# Change the fill color to blue
fill.color = "blue"
canvas.redraw()
# Remove the rectangle from the canvas
fill.remove(rect)
For detailed tutorials on the use of Canvas drawing instructions, 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¶
- 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.
Reference¶
toga.Canvas ¶
Canvas(
id=None,
style=None,
on_resize=None,
on_press=None,
on_activate=None,
on_release=None,
on_drag=None,
on_alt_press=None,
on_alt_release=None,
on_alt_drag=None,
**kwargs,
)
Bases: Widget
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:
|
enabled
property
writable
¶
enabled
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
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
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
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
The handler to invoke when an alternate press is released.
This event is not supported on Android or iOS.
on_press
property
writable
¶
on_press
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.
ClosedPath ¶
ClosedPath(x=None, y=None)
Construct and yield a new
ClosedPathContext
context in the root context of this canvas.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The x coordinate of the path's starting point.
TYPE:
|
y
|
The y coordinate of the path's starting point.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AbstractContextManager[ClosedPathContext]
|
Yields the new |
Context ¶
Context()
Construct and yield a new sub-Context within
the root context of this Canvas.
| RETURNS | DESCRIPTION |
|---|---|
AbstractContextManager[Context]
|
Yields the new |
Fill ¶
Fill(x=None, y=None, color=BLACK, fill_rule=FillRule.NONZERO)
Construct and yield a new FillContext
in the root context of this canvas.
A drawing operator that fills the path constructed in the context according to the current fill rule.
If both an x and y coordinate is provided, the drawing context will begin with
a move_to operation in that context.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The x coordinate of the path's starting point.
TYPE:
|
y
|
The y coordinate of the path's starting point.
TYPE:
|
fill_rule
|
|
color
|
The fill color.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AbstractContextManager[FillContext]
|
Yields the new |
Stroke ¶
Stroke(x=None, y=None, color=BLACK, line_width=2.0, line_dash=None)
Construct and yield a new
StrokeContext in the
root context of this canvas.
If both an x and y coordinate is provided, the drawing context will begin with
a move_to operation in that context.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The x coordinate of the path's starting point.
TYPE:
|
y
|
The y coordinate of the path's starting point.
TYPE:
|
color
|
The color for the stroke.
TYPE:
|
line_width
|
The width of the stroke.
TYPE:
|
line_dash
|
The dash pattern to follow when drawing the line. Default is a solid line. |
| RETURNS | DESCRIPTION |
|---|---|
AbstractContextManager[StrokeContext]
|
Yields the new |
as_image ¶
as_image(format=toga.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. |
measure_text ¶
measure_text(text, font=None, line_height=None)
Measure the size at which
Context.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 |
redraw ¶
redraw()
Redraw the Canvas.
The Canvas will be automatically redrawn after adding or removing a drawing
object, or when the Canvas resizes. However, when you modify the properties of a
drawing object, you must call redraw manually.
toga.widgets.canvas.Context ¶
Context(canvas, **kwargs)
Bases: DrawingObject
A drawing context for a canvas.
You should not create a Context directly; instead,
you should use the Context() method on an
existing context, or use Canvas.context to access the root
context of the canvas.
ClosedPath ¶
ClosedPath(x=None, y=None)
Construct and yield a new ClosedPath
sub-context that will draw a closed path, starting from an origin.
This is a context manager; it creates a new path and moves to the start
coordinate; when the context exits, the path is closed. For fine-grained control
of a path, you can use begin_path
and close_path.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The x coordinate of the path's starting point.
TYPE:
|
y
|
The y coordinate of the path's starting point.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterator[ClosedPathContext]
|
Yields the |
Context ¶
Context()
Fill ¶
Fill(x=None, y=None, color=BLACK, fill_rule=FillRule.NONZERO)
Construct and yield a new Fill sub-context
within this context.
This is a context manager; it creates a new path, and moves to the start
coordinate; when the context exits, the path is closed with a fill. For
fine-grained control of a path, you can use
begin_path,
move_to,
close_path and
fill.
If both an x and y coordinate is provided, the drawing context will begin with
a move_to operation in that context.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The x coordinate of the path's starting point.
TYPE:
|
y
|
The y coordinate of the path's starting point.
TYPE:
|
fill_rule
|
|
color
|
The fill color.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterator[FillContext]
|
Yields the new |
Stroke ¶
Stroke(x=None, y=None, color=BLACK, line_width=2.0, line_dash=None)
Construct and yield a new Stroke sub-context
within this context.
This is a context manager; it creates a new path, and moves to the start
coordinate; when the context exits, the path is closed with a stroke. For
fine-grained control of a path, you can use
begin_path,
move_to,
close_path and
stroke.
If both an x and y coordinate is provided, the drawing context will begin with
a move_to operation in that context.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
The x coordinate of the path's starting point.
TYPE:
|
y
|
The y coordinate of the path's starting point.
TYPE:
|
color
|
The color for the stroke.
TYPE:
|
line_width
|
The width of the stroke.
TYPE:
|
line_dash
|
The dash pattern to follow when drawing the line. Default is a solid line. |
| RETURNS | DESCRIPTION |
|---|---|
Iterator[StrokeContext]
|
Yields the new |
append ¶
append(obj)
Append a drawing object to the context.
| PARAMETER | DESCRIPTION |
|---|---|
obj
|
The drawing object to add to the context.
TYPE:
|
arc ¶
arc(
x,
y,
radius,
startangle=0.0,
endangle=2 * pi,
counterclockwise=None,
anticlockwise=None,
)
Draw a circular arc in the canvas context.
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 |
begin_path ¶
begin_path()
Start a new path in the canvas context.
| RETURNS | DESCRIPTION |
|---|---|
BeginPath
|
The |
bezier_curve_to ¶
bezier_curve_to(cp1x, cp1y, cp2x, cp2y, x, y)
Draw a Bézier curve in the canvas context.
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 |
close_path ¶
close_path()
Close the current path in the canvas context.
This closes the current path as a simple drawing operation. It should be paired
with a begin_path() operation; or,
to complete a complete closed path, use the
ClosedPath() context manager.
| RETURNS | DESCRIPTION |
|---|---|
ClosePath
|
The |
ellipse ¶
ellipse(
x,
y,
radiusx,
radiusy,
rotation=0.0,
startangle=0.0,
endangle=2 * pi,
counterclockwise=None,
anticlockwise=None,
)
Draw an elliptical arc in the canvas context.
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 |
fill ¶
fill(color=BLACK, fill_rule=FillRule.NONZERO)
Fill the current path.
The fill can use either the Non-Zero or Even-Odd winding rule for filling paths.
| PARAMETER | DESCRIPTION |
|---|---|
fill_rule
|
|
color
|
The fill color.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Fill
|
The |
insert ¶
insert(index, obj)
Insert a drawing object into the context at a specific index.
| PARAMETER | DESCRIPTION |
|---|---|
index
|
The index at which the drawing object should be inserted.
TYPE:
|
obj
|
The drawing object to add to the context.
TYPE:
|
line_to ¶
line_to(x, y)
Draw a line segment ending at a point in the canvas context.
| 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 |
move_to ¶
move_to(x, y)
Moves the current point of the canvas context 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 |
quadratic_curve_to ¶
quadratic_curve_to(cpx, cpy, x, y)
Draw a quadratic curve in the canvas context.
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 |
rect ¶
rect(x, y, width, height)
Draw a rectangle in the canvas context.
| 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 |
remove ¶
remove(obj)
Remove a drawing object from the context.
| PARAMETER | DESCRIPTION |
|---|---|
obj
|
The drawing object to remove.
TYPE:
|
reset_transform ¶
reset_transform()
Reset all transformations in the canvas context.
| RETURNS | DESCRIPTION |
|---|---|
ResetTransform
|
A |
rotate ¶
rotate(radians)
Add a rotation to the canvas context.
| PARAMETER | DESCRIPTION |
|---|---|
radians
|
The angle to rotate clockwise in radians.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Rotate
|
The |
scale ¶
scale(sx, sy)
Add a scaling transformation to the canvas context.
| 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 |
stroke ¶
stroke(color=BLACK, line_width=2.0, line_dash=None)
Draw the current path as a stroke.
| PARAMETER | DESCRIPTION |
|---|---|
color
|
The color for the stroke.
TYPE:
|
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 |
|---|---|
Stroke
|
The |
translate ¶
translate(tx, ty)
Add a translation to the canvas context.
| PARAMETER | DESCRIPTION |
|---|---|
tx
|
Translation for the X dimension.
TYPE:
|
ty
|
Translation for the Y dimension.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Translate
|
The |
write_text ¶
write_text(
text,
x=0.0,
y=0.0,
font=None,
baseline=Baseline.ALPHABETIC,
line_height=None,
)
Write text at a given position in the canvas context.
Drawing text is effectively a series of path operations, so the text will have the color and fill properties of the canvas context.
| 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 |
toga.widgets.canvas.DrawingObject ¶
Bases: ABC
A drawing operation in a Context.
Every context drawing method creates a DrawingObject, adds it to the context,
and returns it. Each argument passed to the method becomes a property of the
DrawingObject, which can be modified as shown in the Usage section.
DrawingObjects can also be created manually, then added to a context using the
append() or
insert() methods. Their constructors take
the same arguments as the corresponding Context
method, and their classes have the same names, but capitalized:
toga.widgets.canvas.Arctoga.widgets.canvas.BeginPathtoga.widgets.canvas.BezierCurveTotoga.widgets.canvas.ClosePathtoga.widgets.canvas.Ellipsetoga.widgets.canvas.Filltoga.widgets.canvas.LineTotoga.widgets.canvas.MoveTotoga.widgets.canvas.QuadraticCurveTotoga.widgets.canvas.Recttoga.widgets.canvas.ResetTransformtoga.widgets.canvas.Rotatetoga.widgets.canvas.Scaletoga.widgets.canvas.Stroketoga.widgets.canvas.Translatetoga.widgets.canvas.WriteText
toga.widgets.canvas.ClosedPathContext ¶
ClosedPathContext(canvas, x=None, y=None)
Bases: Context
A drawing context that will build a closed path, starting from an origin.
This is a context manager; it creates a new path and moves to the start coordinate;
when the context exits, the path is closed. For fine-grained control of a path, you
can use begin_path,
move_to and,
close_path.
If both an x and y coordinate is provided, the drawing context will begin with
a move_to operation in that context.
You should not create a ClosedPathContext
context directly; instead, you should use the
ClosedPath() method on an existing
context.
toga.widgets.canvas.FillContext ¶
FillContext(canvas, x=None, y=None, color=BLACK, fill_rule=FillRule.NONZERO)
Bases: ClosedPathContext
A drawing context that will apply a fill to any paths all objects in the context.
The fill can use either the Non-Zero or Even-Odd winding rule for filling paths.
This is a context manager; it creates a new path, and moves to the start coordinate;
when the context exits, the path is closed with a fill. For fine-grained control of
a path, you can use begin_path,
move_to,
close_path and
fill.
If both an x and y coordinate is provided, the drawing context will begin with
a move_to operation in that context.
You should not create a FillContext context
directly; instead, you should use the Fill()
method on an existing context.
toga.widgets.canvas.StrokeContext ¶
StrokeContext(
canvas, x=None, y=None, color=BLACK, line_width=2.0, line_dash=None
)
Bases: ClosedPathContext
Construct a drawing context that will draw a stroke on all paths defined within the context.
This is a context manager; it creates a new path, and moves to the start coordinate;
when the context exits, the path is drawn with the stroke. For fine-grained control
of a path, you can use begin_path,
move_to,
close_path and
stroke.
If both an x and y coordinate is provided, the drawing context will begin with
a move_to operation in that context.
You should not create a StrokeContext context
directly; instead, you should use the
Stroke() method on an existing context.
toga.widgets.canvas.OnTouchHandler ¶
Bases: Protocol
__call__ ¶
__call__(widget, x, y, **kwargs)
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:
|