Skip to content

Canvas

A drawing area for 2D vector graphics.

Canvas on macOS

Canvas on Linux (GTK)

Canvas on Linux (Qt)

Canvas on Windows

Canvas on iOS

Canvas on Android

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:

Usage example

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: 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: {}

fill_style class-attribute instance-attribute

fill_style: ColorT

The current fill color.

stroke_style class-attribute instance-attribute

stroke_style: ColorT

The current stroke color.

line_width class-attribute instance-attribute

line_width: float

The current width of the stroke.

line_dash class-attribute instance-attribute

line_dash: list[float]

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.

root_state property

root_state: State

The root state for the canvas. See DrawingAction.

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 Save DrawingAction for the operation.

restore

restore() -> Save

Restore to the previous state of the drawing context.

RETURNS DESCRIPTION
Save

The Restore DrawingAction for the operation.

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

begin_path

begin_path() -> BeginPath

Start a new path.

RETURNS DESCRIPTION
BeginPath

The BeginPath DrawingAction for the operation.

close_path

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

move_to

move_to(x: float, y: float) -> MoveTo

Moves the current point 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 DrawingAction for the operation.

line_to

line_to(x: float, y: float) -> LineTo

Draw a line segment ending at a point.

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

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: 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 DrawingAction for the operation.

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: 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 DrawingAction for the operation.

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: 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 DrawingAction for the operation.

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: 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 DrawingAction for the operation.

rect

rect(x: float, y: float, width: float, height: float) -> Rect

Draw a rectangle.

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

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

y

The vertical coordinate of the top of the rounded rectangle.

TYPE: float

width

The width of the rounded rectangle.

TYPE: float

height

The height of the roundedrectangle.

TYPE: float

radii

The corner radii of the rounded rectangle.

TYPE: float | CornerRadiusT | Iterable[float | CornerRadiusT]

RETURNS DESCRIPTION
RoundRect

The RoundRect DrawingAction for the operation.

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

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

TYPE: FillRule DEFAULT: NONZERO

fill_style

The fill style. At present, only accepts colors; gradients and patterns are not supported.

TYPE: ColorT | None | object DEFAULT: NOT_PROVIDED

color

Alias for fill_style.

TYPE: ColorT | None | object DEFAULT: NOT_PROVIDED

RETURNS DESCRIPTION
AbstractContextManager[Fill]

The Fill DrawingAction for the operation.

RAISES DESCRIPTION
TypeError

If both fill_style and color are provided.

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.

TYPE: ColorT | None | object DEFAULT: NOT_PROVIDED

color

Alias for fill_style.

TYPE: ColorT | None | object DEFAULT: NOT_PROVIDED

line_width

The width of the stroke.

TYPE: float | None DEFAULT: None

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
AbstractContextManager[Stroke]

The Stroke DrawingAction for the operation.

RAISES DESCRIPTION
TypeError

If both stroke_style and color are provided.

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: 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 DrawingAction for the operation.

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

x

The x-coordinate of the bottom-left corner of the image when it is drawn.

TYPE: float DEFAULT: 0.0

y

The y-coordinate of the bottom-left corner of the image when it is drawn.

TYPE: float DEFAULT: 0.0

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

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

rotate

rotate(radians: float) -> Rotate

Add a rotation.

PARAMETER DESCRIPTION
radians

The angle to rotate clockwise in radians.

TYPE: float

RETURNS DESCRIPTION
Rotate

The Rotate DrawingAction for the transformation.

scale

scale(sx: float, sy: float) -> Scale

Add a scaling transformation.

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 DrawingAction for the transformation.

translate

translate(tx: float, ty: float) -> Translate

Add a translation.

PARAMETER DESCRIPTION
tx

Translation for the X dimension.

TYPE: float

ty

Translation for the Y dimension.

TYPE: float

RETURNS DESCRIPTION
Translate

The Translate DrawingAction for the transformation.

reset_transform

reset_transform() -> ResetTransform

Reset all transformations.

RETURNS DESCRIPTION
ResetTransform

A ResetTransform DrawingAction.

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

as_image

as_image(format: type[ImageT] = Image) -> ImageT

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() -> None

No-op; Canvas cannot accept input focus.

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__

__call__(widget: Canvas, x: int, y: int, **kwargs: Any) -> None

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: Canvas, width: int, height: int, **kwargs: Any) -> None

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: {}