Canvas

Canvas

A fixed-size drawing surface. Canvas takes a list of drawing commands from nib.draw (shapes, paths, images, text) and paints them with Core Graphics on a layer that draws asynchronously.

draw(), append() and clear() request a render. Gesture callbacks report pointer positions for sketching and annotation tools.

For the full list of drawing commands, see the Draw Module Reference.

Constructor

nib.Canvas(
    width=100,
    height=100,
    commands=None,
    background_color=None,
    enable_gestures=False,
    on_pan_start=None,
    on_pan_update=None,
    on_pan_end=None,
    on_mouse_move=None,
    **modifiers,
)

Parameters

Parameter Type Default Description
width float 100 Width of the canvas drawing area in points.
height float 100 Height of the canvas drawing area in points.
commands list[DrawCommand] None Initial list of drawing commands to render.
background_color str | Color None Background color, a hex string ("#1a1a1a") or nib.Color. None for transparent.
enable_gestures bool False Enable pan and hover tracking. Turned on when any gesture callback is passed.
on_pan_start Callable[[PanEvent], None] None Callback invoked when mouse/pen is pressed down on the canvas.
on_pan_update Callable[[PanEvent], None] None Callback invoked when mouse/pen is dragged across the canvas.
on_pan_end Callable[[PanEvent], None] None Callback invoked when mouse/pen is released.
on_mouse_move Callable[[PanEvent], None] None Callback with the position as the pointer moves over the canvas with no button pressed. on_hover, shared by every view, reports entering and leaving with a bool.
**modifiers Common view modifiers: padding, opacity, corner_radius, etc.

Mutable Properties

Property Type Description
canvas_width float Get or set the drawing area width. Setting triggers a re-render.
canvas_height float Get or set the drawing area height. Setting triggers a re-render.
background_color str | None Get or set the background color.
commands list[DrawCommand] Get the current list of drawing commands (read-only).
on_pan_start Callable | None Get or set the pan start callback. Assigning a callback enables gestures.
on_pan_update Callable | None Get or set the pan update callback. Assigning a callback enables gestures.
on_pan_end Callable | None Get or set the pan end callback. Assigning a callback enables gestures.
on_mouse_move Callable | None Get or set the pointer callback. Assigning a callback enables gestures.

Assigning a gesture callback after construction turns gesture tracking on.

Coordinates and size

The origin is the top-left corner of the canvas and y grows downward. Command coordinates, gradient points and PanEvent positions all use this space, in points.

width and height in the constructor set the drawing size (canvas_width and canvas_height). Change the drawing size later through those two properties:

canvas = nib.Canvas(width=200, height=100)
canvas.canvas_width = 300  # the drawing area is now 300 x 100

Assigning canvas.width or canvas.height after construction adds a frame modifier around the canvas. The drawing area keeps its size; the frame only changes the space the canvas takes in the layout.

Drawing and updating

Call Effect
Canvas(commands=[...]) Initial command list.
canvas.draw(commands) Replace every command. A list equal to the current one is a no-op.
canvas.append(command) Add one command at the end.
canvas.clear() Remove every command.

Commands paint in list order, so later commands draw over earlier ones. The runtime keeps what it has painted: when the new list starts with the commands already painted (an append), it paints only the new ones. Any other change repaints the whole list. For drawings that grow, such as freehand strokes, append keeps each update cheap.

Animation

To animate, rebuild the command list and call draw() per frame from a thread. draw() is safe from any thread. See Threads and long work.

import math, threading, time
import nib

def main(app: nib.App):
    canvas = nib.Canvas(width=200, height=200, background_color="#1a1a1a")

    def animate():
        t = 0.0
        while app.is_running:
            x = 100 + 60 * math.cos(t)
            y = 100 + 60 * math.sin(t)
            canvas.draw([nib.draw.Circle(cx=x, cy=y, radius=12, fill="#e74c3c")])
            t += 0.1
            time.sleep(1 / 30)

    threading.Thread(target=animate, daemon=True).start()
    app.build(canvas)

nib.run(main)

The Waveform example redraws a canvas 25 times a second this way.

Gestures

Gesture tracking is off by default. Pass enable_gestures=True or any gesture callback to turn it on. Each callback receives a PanEvent with the pointer position in canvas coordinates.

Callback Fires when
on_pan_start A mouse button is pressed on the canvas.
on_pan_update The pointer moves with the button held.
on_pan_end The button is released.
on_mouse_move The pointer moves over the canvas with no button pressed.

Hover events stop during a drag; on_pan_update reports those positions instead. The freehand drawing example below appends a Line per on_pan_update.

Methods

Method Signature Description
draw draw(commands: list[DrawCommand]) Replace all drawing commands and re-render.
append append(command: DrawCommand) Add a single drawing command and re-render.
clear clear() Remove all drawing commands and re-render.

PanEvent

A dataclass passed to gesture callbacks containing the pointer position.

Field Type Description
x float X coordinate of the event in canvas coordinates.
y float Y coordinate of the event in canvas coordinates.

Examples

Basic drawing

canvas_basic_drawing

import nib


def main(app: nib.App):
    app.title = "Canvas"
    app.icon = nib.SFSymbol("paintbrush.pointed")
    app.width = 360
    app.height = 240

    canvas = nib.Canvas(width=320, height=200, background_color="#1c1c1e")
    canvas.draw(
        [
            nib.draw.Rect(
                x=20, y=20, width=120, height=70, corner_radius=10, fill="#0a84ff"
            ),
            nib.draw.Circle(cx=230, cy=60, radius=40, fill="#ff453a"),
            nib.draw.Line(
                x1=20, y1=130, x2=300, y2=130, stroke="#30d158", stroke_width=4
            ),
            nib.draw.Text(
                "Core Graphics, from Python",
                x=160,
                y=155,
                fill="#ffffff",
                alignment=nib.HorizontalAlignment.CENTER,
            ),
        ]
    )

    app.build(nib.VStack(controls=[canvas], padding=16))


nib.run(main)

Freehand drawing with gestures

canvas_freehand_drawing_gestures

import nib


def main(app: nib.App):
    app.title = "Sketch"
    app.icon = nib.SFSymbol("pencil.tip")
    app.width = 360
    app.height = 300

    canvas = nib.Canvas(width=320, height=220, background_color="#ffffff")
    last = None

    def on_pan_start(e):
        nonlocal last
        last = (e.x, e.y)

    def on_pan_update(e):
        nonlocal last
        canvas.append(
            nib.draw.Line(
                x1=last[0], y1=last[1], x2=e.x, y2=e.y, stroke="#1c1c1e", stroke_width=3
            )
        )
        last = (e.x, e.y)

    canvas.on_pan_start = on_pan_start
    canvas.on_pan_update = on_pan_update

    app.build(
        nib.VStack(
            controls=[
                canvas,
                nib.HStack(
                    controls=[
                        nib.Text(
                            "Draw with the mouse", foreground_color=nib.Color.SECONDARY
                        ),
                        nib.Spacer(),
                        nib.Button("Clear", on_click=canvas.clear),
                    ]
                ),
            ],
            spacing=8,
            padding=16,
        )
    )


nib.run(main)