Skip to content
Toga
0.5.3.dev143+gabcc6cdb6

Canvas

A drawing area for 2D vector graphics.

/reference/images/canvas-cocoa.png

/reference/images/canvas-gtk.png

/reference/images/canvas-winforms.png

/reference/images/canvas-android.png

/reference/images/canvas-iOS.png

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: str | None DEFAULT: None

style

A style object. If no style is provided, a default style will be applied to the widget.

TYPE: StyleT | None DEFAULT: None

on_resize

Initial on_resize handler.

TYPE: OnResizeHandler | None DEFAULT: None

on_press

Initial on_press handler.

TYPE: OnTouchHandler | None DEFAULT: None

on_activate

Initial on_activate handler.

TYPE: OnTouchHandler | None DEFAULT: None

on_release

Initial on_release handler.

TYPE: OnTouchHandler | None DEFAULT: None

on_drag

Initial on_drag handler.

TYPE: OnTouchHandler | None DEFAULT: None

on_alt_press

Initial on_alt_press handler.

TYPE: OnTouchHandler | None DEFAULT: None

on_alt_release

Initial on_alt_release handler.

TYPE: OnTouchHandler | None DEFAULT: None

on_alt_drag

Initial on_alt_drag handler.

TYPE: OnTouchHandler | None DEFAULT: None

kwargs

Initial style properties.

DEFAULT: {}

context property

context

The root context for the canvas.

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_drag property writable

on_drag

The handler invoked when the location of a press changes.

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.

on_release property writable

on_release

The handler invoked when a press on the canvas ends.

on_resize property writable

on_resize

The handler to invoke when the canvas is resized.

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: float | None DEFAULT: None

y

The y coordinate of the path's starting point.

TYPE: float | None DEFAULT: None

RETURNS DESCRIPTION
AbstractContextManager[ClosedPathContext]

Yields the new ClosedPathContext context object.

Context

Context()

Construct and yield a new sub-Context within the root context of this Canvas.

RETURNS DESCRIPTION
AbstractContextManager[Context]

Yields the new Context object.

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: float | None DEFAULT: None

y

The y coordinate of the path's starting point.

TYPE: float | None DEFAULT: None

fill_rule

nonzero is the non-zero winding rule; evenodd is the even-odd winding rule.

TYPE: FillRule DEFAULT: NONZERO

color

The fill color.

TYPE: Color | str | None DEFAULT: BLACK

RETURNS DESCRIPTION
AbstractContextManager[FillContext]

Yields the new FillContext context object.

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: float | None DEFAULT: None

y

The y coordinate of the path's starting point.

TYPE: float | None DEFAULT: None

color

The color for the stroke.

TYPE: Color | str | None DEFAULT: BLACK

line_width

The width of the stroke.

TYPE: float DEFAULT: 2.0

line_dash

The dash pattern to follow when drawing the line. Default is a solid line.

TYPE: list[float] | None DEFAULT: None

RETURNS DESCRIPTION
AbstractContextManager[StrokeContext]

Yields the new StrokeContext context object.

as_image

as_image(format=toga.Image)

Render the canvas as an image.

PARAMETER DESCRIPTION
format

Format to provide. Defaults to Image; also supports PIL.Image.Image if Pillow is installed, as well as any image types defined by installed image format plugins.

TYPE: type[ImageT] DEFAULT: Image

RETURNS DESCRIPTION
ImageT

The canvas as an image of the specified type.

focus

focus()

No-op; Canvas cannot accept input focus.

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: str

font

The font in which to draw the text. The default is the system font.

TYPE: Font | None DEFAULT: None

line_height

Height of the line box as a multiple of the font size when multiple lines are present.

TYPE: float | None DEFAULT: None

RETURNS DESCRIPTION
tuple[float, float]

A tuple of (width, height).

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.

canvas property

canvas

The canvas that is associated with this drawing context.

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: float | None DEFAULT: None

y

The y coordinate of the path's starting point.

TYPE: float | None DEFAULT: None

RETURNS DESCRIPTION
Iterator[ClosedPathContext]

Yields the ClosedPathContext context object.

Context

Context()

Construct and yield a new sub-Context within this context.

RETURNS DESCRIPTION
Iterator[Context]

Yields the new Context object.

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: float | None DEFAULT: None

y

The y coordinate of the path's starting point.

TYPE: float | None DEFAULT: None

fill_rule

nonzero is the non-zero winding rule; evenodd is the even-odd winding rule.

TYPE: FillRule DEFAULT: NONZERO

color

The fill color.

TYPE: str DEFAULT: BLACK

RETURNS DESCRIPTION
Iterator[FillContext]

Yields the new FilContext context object.

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: float | None DEFAULT: None

y

The y coordinate of the path's starting point.

TYPE: float | None DEFAULT: None

color

The color for the stroke.

TYPE: str DEFAULT: BLACK

line_width

The width of the stroke.

TYPE: float DEFAULT: 2.0

line_dash

The dash pattern to follow when drawing the line. Default is a solid line.

TYPE: list[float] | None DEFAULT: None

RETURNS DESCRIPTION
Iterator[StrokeContext]

Yields the new StrokeContext context object.

__getitem__

__getitem__(index)

Returns the drawing object at the given index.

__len__

__len__()

Returns the number of drawing objects that are in this context.

append

append(obj)

Append a drawing object to the context.

PARAMETER DESCRIPTION
obj

The drawing object to add to the context.

TYPE: DrawingObject

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: float

y

The Y coordinate of the circle's center.

TYPE: float

startangle

The start angle in radians, measured clockwise from the positive X axis.

TYPE: float DEFAULT: 0.0

endangle

The end angle in radians, measured clockwise from the positive X axis.

TYPE: float DEFAULT: 2 * pi

counterclockwise

If true, the arc is swept counterclockwise. The default is clockwise.

TYPE: bool | None DEFAULT: None

anticlockwise

DEPRECATED - Use counterclockwise.

TYPE: bool | None DEFAULT: None

RETURNS DESCRIPTION
Arc

The Arc DrawingObject for the operation.

begin_path

begin_path()

Start a new path in the canvas context.

RETURNS DESCRIPTION
BeginPath

The BeginPath DrawingObject for the operation.

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: float

cp1x

The x coordinate for the first control point of the Bézier curve.

TYPE: float

cp2x

The x coordinate for the second control point of the Bézier curve.

TYPE: float

cp2y

The y coordinate for the second control point of the Bézier curve.

TYPE: float

x

The x coordinate for the end point.

TYPE: float

y

The y coordinate for the end point.

TYPE: float

RETURNS DESCRIPTION
BezierCurveTo

The BezierCurveTo DrawingObject for the operation.

clear

clear()

Remove all drawing objects from the context.

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 ClosePath DrawingObject for the operation.

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: float

y

The Y coordinate of the ellipse's center.

TYPE: float

radiusx

The ellipse's horizontal axis radius.

TYPE: float

radiusy

The ellipse's vertical axis radius.

TYPE: float

rotation

The ellipse's rotation in radians, measured clockwise around its center.

TYPE: float DEFAULT: 0.0

startangle

The start angle in radians, measured clockwise from the positive X axis.

TYPE: float DEFAULT: 0.0

endangle

The end angle in radians, measured clockwise from the positive X axis.

TYPE: float DEFAULT: 2 * pi

counterclockwise

If true, the arc is swept counterclockwise. The default is clockwise.

TYPE: bool | None DEFAULT: None

anticlockwise

DEPRECATED - Use counterclockwise.

TYPE: bool | None DEFAULT: None

RETURNS DESCRIPTION
Ellipse

The Ellipse DrawingObject for the operation.

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

nonzero is the non-zero winding rule; evenodd is the even-odd winding rule.

TYPE: FillRule DEFAULT: NONZERO

color

The fill color.

TYPE: str DEFAULT: BLACK

RETURNS DESCRIPTION
Fill

The Fill DrawingObject for the operation.

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: int

obj

The drawing object to add to the context.

TYPE: DrawingObject

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: float

y

The y coordinate for the end point of the line segment.

TYPE: float

RETURNS DESCRIPTION
LineTo

The LineTo DrawingObject for the operation.

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: float

y

The y coordinate of the new current point.

TYPE: float

RETURNS DESCRIPTION
MoveTo

The MoveTo DrawingObject for the operation.

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: float

cpy

The y axis of the coordinate for the control point of the quadratic curve.

TYPE: float

x

The x axis of the coordinate for the end point.

TYPE: float

y

The y axis of the coordinate for the end point.

TYPE: float

RETURNS DESCRIPTION
QuadraticCurveTo

The QuadraticCurveTo DrawingObject for the operation.

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: float

y

The vertical coordinate of the top of the rectangle.

TYPE: float

width

The width of the rectangle.

TYPE: float

height

The height of the rectangle.

TYPE: float

RETURNS DESCRIPTION
Rect

The Rect DrawingObject for the operation.

redraw

redraw()

Calls Canvas.redraw on the parent Canvas.

remove

remove(obj)

Remove a drawing object from the context.

PARAMETER DESCRIPTION
obj

The drawing object to remove.

TYPE: DrawingObject

reset_transform

reset_transform()

Reset all transformations in the canvas context.

RETURNS DESCRIPTION
ResetTransform

A ResetTransform DrawingObject.

rotate

rotate(radians)

Add a rotation to the canvas context.

PARAMETER DESCRIPTION
radians

The angle to rotate clockwise in radians.

TYPE: float

RETURNS DESCRIPTION
Rotate

The Rotate DrawingObject for the transformation.

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: float

sy

Scale factor for the Y dimension. A negative value flips the image vertically.

TYPE: float

RETURNS DESCRIPTION
Scale

The Scale DrawingObject for the transformation.

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: str DEFAULT: BLACK

line_width

The width of the stroke.

TYPE: float DEFAULT: 2.0

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.

TYPE: list[float] | None DEFAULT: None

RETURNS DESCRIPTION
Stroke

The Stroke DrawingObject for the operation.

translate

translate(tx, ty)

Add a translation to the canvas context.

PARAMETER DESCRIPTION
tx

Translation for the X dimension.

TYPE: float

ty

Translation for the Y dimension.

TYPE: float

RETURNS DESCRIPTION
Translate

The Translate DrawingObject for the transformation.

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: str

x

The X coordinate of the text's left edge.

TYPE: float DEFAULT: 0.0

y

The Y coordinate: its meaning depends on baseline.

TYPE: float DEFAULT: 0.0

font

The font in which to draw the text. The default is the system font.

TYPE: Font | None DEFAULT: None

baseline

Alignment of text relative to the Y coordinate.

TYPE: Baseline DEFAULT: ALPHABETIC

line_height

Height of the line box as a multiple of the font size when multiple lines are present.

TYPE: float | None DEFAULT: None

RETURNS DESCRIPTION
WriteText

The WriteText DrawingObject for the operation.

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.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.

color property writable

color

The fill color.

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.

color property writable

color

The color of the stroke.

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: Canvas

x

X coordinate, relative to the left edge of the canvas.

TYPE: int

y

Y coordinate, relative to the top edge of the canvas.

TYPE: int

kwargs

Ensures compatibility with arguments added in future versions.

TYPE: Any DEFAULT: {}

toga.widgets.canvas.OnResizeHandler

Bases: Protocol

__call__

__call__(widget, width, height, **kwargs)

A handler that will be invoked when a Canvas is resized.

PARAMETER DESCRIPTION
widget

The canvas that was resized.

TYPE: Canvas

width

The new width.

TYPE: int

height

The new height.

TYPE: int

kwargs

Ensures compatibility with arguments added in future versions.

TYPE: Any DEFAULT: {}