ipycanvas

Draw on a live HTML canvas from Python, and read mouse and keyboard events straight back into Shiny’s reactive graph.

ipycanvas is a Python binding to the browser’s HTML5 canvas: draw shapes, paths, text, gradients, and pixel data with plain method calls, a fit for sketch pads, pixel editors, cellular automata, and click-to-annotate tools. @render_ipycanvas renders a Canvas, MultiCanvas, RoughCanvas, or MultiRoughCanvas, and keeps .widget live so you can draw on it from any reactive context without re-rendering.

hero

A tiny scikit-learn model guesses the digit as you draw it. Try the app.

Installation

pip install 'shinywidgets[ipycanvas]'

ipycanvas is pure Python with no native dependencies, so this resolves on every Python version shinywidgets supports.

Quick start

A Canvas is a drawing surface sized in buffer pixels. Draw on it once at render time with the same method calls you’d use in a Jupyter notebook:

from ipycanvas import Canvas
from shiny.express import ui
from shinywidgets import render_ipycanvas

ui.page_opts(title="ipycanvas quickstart", fillable=True)

with ui.card(full_screen=True):

    @render_ipycanvas
    def canvas():
        c = Canvas(width=400, height=250)
        c.fill_style = "#f4f1ea"
        c.fill_rect(0, 0, 400, 250)
        c.fill_style = "steelblue"
        c.fill_rect(20, 20, 140, 90)
        c.fill_style = "#e67e22"
        c.fill_circle(260, 90, 55)
        c.font = "20px sans-serif"
        c.fill_style = "#222"
        c.fill_text("Hello from Python", 20, 160)
        return c

quickstart

In a filling layout (ui.card(full_screen=True), no explicit output_widget(height=)), the canvas keeps its 400x250 buffer size and centers itself in the available space – it never stretches to fill.

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

Every canvas method – fill_rect, stroke_circle, stroke_line, fill_text, gradients, clip, transforms, and the rest – is a direct call with no scene graph or re-render step, so ipycanvas doubles as a general-purpose drawing surface for anything a charting library won’t do out of the box.

Canvas features

Two upstream APIs are worth knowing first.

MultiCanvas layers

A MultiCanvas(n, width=, height=) is n independently-addressable canvases (mc[0], mc[1], …) composited into a single element. Put a background that never changes on one layer and foreground ink on another – clearing the ink never touches the background:

examples/03_multicanvas_layers.pyexcerpt · 26 of 38 lines
    @render_ipycanvas
    def mc():
        canvas = MultiCanvas(2, width=W, height=H)
        grid, ink = canvas[0], canvas[1]

        # Layer 0: a dot grid, drawn once -- it's never touched again
        grid.fill_style = "#ccc"
        for x in range(10, W, 20):
            for y in range(10, H, 20):
                grid.fill_circle(x, y, 1.2)

        # Layer 1: a few "sticky note" shapes
        ink.fill_style = "#f1c40f"
        ink.fill_rect(40, 40, 90, 90)
        ink.fill_style = "#e74c3c"
        ink.fill_rect(160, 90, 90, 90)
        ink.fill_style = "#2ecc71"
        ink.fill_rect(260, 50, 90, 90)
        return canvas

    @reactive.effect
    @reactive.event(input.clear)
    def _():
        canvas = mc.widget
        if canvas is not None:
            canvas[1].clear()  # only the ink layer is erased

Pushing pixels with put_image_data

put_image_data(array, x, y) pushes an (h, w, 4) uint8 RGBA numpy array straight onto the canvas – useful for anything you’d rather compute as pixels than as a sequence of shape calls (heatmaps, images, simulation frames):

examples/04_put_image_data.pyexcerpt · 1 of 41 lines
c.put_image_data(corr_to_rgba(corr, CELL), 0, 0)

put_image_data

hold_canvas()

ipycanvas.hold_canvas() has no effect under shinywidgets – the drawing looks the same either way. It’s safe to leave in code shared with Jupyter; it just doesn’t do anything extra here:

examples/07_hold_canvas_noop.pyexcerpt · 4 of 33 lines
with hold_canvas(c):
    for i in range(8):
        c.fill_style = f"hsl({i * 40}, 65%, 55%)"
        c.fill_rect(10 + i * 50, 20, 40, 20 + i * 20)

hold_canvas

Reacting to interaction

ipycanvas declares no accessors: its events are lower-level than “a selection changed” – raw browser events (on_mouse_down, on_mouse_move, on_mouse_up, on_mouse_out, on_mouse_wheel, on_key_down, touch start/end/move/cancel) that call a plain Python function with the event’s data. One recipe turns those callbacks into Shiny reactive values.

Mouse events to reactive values

Register a callback inside the render function. Inside it, read input.*() directly (no reactive context needed there) and call .set() on a reactive.value to publish what happened:

examples/08_mouse_events_recipe.pyexcerpt · 43 of 53 lines
last_point = reactive.value(None)
stroke_count = reactive.value(0)
drawing = {"active": False}

with ui.layout_columns(col_widths=(8, 4)):
    with ui.card(full_screen=True):

        @render_ipycanvas
        def canvas():
            c = Canvas(width=420, height=260)
            c.fill_style = "#f4f1ea"
            c.fill_rect(0, 0, 420, 260)

            def on_down(x, y):
                drawing["active"] = True
                stroke_count.set(stroke_count() + 1)
                last_point.set((x, y))

            def on_move(x, y):
                if not drawing["active"]:
                    return
                c.stroke_style = "#2c7fb8"
                c.line_width = 3
                c.stroke_line(*last_point(), x, y)
                last_point.set((x, y))

            def on_up(x, y):
                drawing["active"] = False

            c.on_mouse_down(on_down)
            c.on_mouse_move(on_move)
            c.on_mouse_up(on_up)
            c.on_mouse_out(on_up)
            return c

    with ui.card():
        ui.card_header("What Python saw")

        @render.text
        def info():
            pt = last_point()
            pt_str = f"{pt[0]:.0f}, {pt[1]:.0f}" if pt else "none yet"
            return f"Strokes started: {stroke_count()}\nLast point: {pt_str}"

(x, y) arrive in drawing-buffer pixels, already correctly scaled even when the canvas is CSS-shrunk by a filling layout. Other outputs read stroke_count()/last_point() like any other reactive value (the info() output above).

Click to place points

A mouse callback that appends to a reactive list, paired with an effect that redraws everything from that list, is the general pattern for any “accumulate points” interaction:

with ui.layout_columns(col_widths=(7, 5)):
    with ui.card(full_screen=True):
        ui.p("Click anywhere on the canvas to drop a point.")

        @render_ipycanvas
        def canvas():
            c = Canvas(width=400, height=280)
            c.fill_style = "#f4f1ea"
            c.fill_rect(0, 0, 400, 280)

            def on_click(x, y):
                points.set(points() + [(x, y)])

            c.on_mouse_down(on_click)
            return c

    with ui.card():
        ui.card_header("Points (click order)")

        @render.data_frame
        def table():
            return pd.DataFrame(points(), columns=["x", "y"])


# Canvas content is stateless (draw commands, not widget state), so the
# simplest way to keep it in sync with `points` is to redraw everything each
# time it changes: clear, then replay.
@reactive.effect
def _draw_points():
    c = canvas.widget
    if c is None:
        return
    c.clear()
    c.fill_style = "#f4f1ea"
    c.fill_rect(0, 0, 400, 280)
    c.fill_style = "#c0392b"
    for x, y in points():
        c.fill_circle(x, y, 6)

Keyboard events

A canvas is focusable (tabindex=0): click it once, then on_key_down(key, shift_key, ctrl_key, meta_key) fires like any other keydown handler:

examples/09_keyboard_recipe.pyexcerpt · 8 of 49 lines
def on_key(key, shift_key, ctrl_key, meta_key):
    last_key.set(key)
    dx, dy = MOVES.get(key, (0, 0))
    pos["x"] = min(max(pos["x"] + dx, 0), 290)
    pos["y"] = min(max(pos["y"] + dy, 0), 210)
    redraw()

c.on_key_down(on_key)

Reading pixels with .read()

For one specific trait, reading it reactively works too: set sync_image_data=True on the constructor, and the browser pushes the composited bitmap back to Python as PNG bytes on the image_data trait. canvas.read("image_data") is the shortcut for this (the same as reactive_read(canvas.widget, "image_data"), since render_ipycanvas has no accessor for it – see Reacting to widgets for when each form applies). Drawing a stroke changes the synced image_data bytes, and canvas.read("image_data") picks up the change – the bridge for anything that needs to see what was drawn, not just where: classifying a sketch, cropping a signature, saving a snapshot.

c = Canvas(width=SIZE, height=SIZE, sync_image_data=True)
...
png_bytes = canvas.read("image_data")
if png_bytes is not None:
    img = Image.open(io.BytesIO(png_bytes))

No other ipycanvas trait is worth reading reactively: width/height are set by you, not the browser, and everything else is write-only draw state.

Classify a drawn digit

sync_image_data plus .read() turns ink into pixels Python can hand to any model. Here, a scikit-learn SVM trained on handwritten digits classifies whatever you draw:

        @render.text
        def guess():
            png_bytes = canvas.read("image_data")
            if png_bytes is None:
                return "Draw something!"
            img = Image.open(io.BytesIO(png_bytes)).convert("L").resize((8, 8))
            pixels = np.asarray(img, dtype=float) / 255 * 16  # match 0-16 scale
            pred = clf.predict(pixels.reshape(1, -1))[0]
            return f"That looks like a {pred}"

The digit sketchpad showcase adds confidence bars and a running tally.

Rate limiting

There’s no built-in rate policy for raw callbacks (that’s an accessor-only feature). on_mouse_move fires on every browser mousemove, with no batching or throttling of its own. Throttle yourself with a timestamp gate, keeping a cheap counter ungated if you want every event to register and a throttled one to drive expensive downstream work:

examples/10_rate_limiting.pyexcerpt · 7 of 45 lines
def on_move(x, y):
    event_count.set(event_count() + 1)  # cheap, update every time
    now = time.monotonic()
    if now - _last_sample["t"] < THROTTLE_S:
        return  # too soon since the last sample -- drop it
    _last_sample["t"] = now
    sampled_count.set(sampled_count() + 1)  # drives expensive work

examples/10_rate_limiting.py throttles the raw events down to a sample every 100ms.

rate limiting

Updating in place

Draw on .widget from a @reactive.effect to update the canvas in place, without re-rendering the function that created it. This matters because re-rendering tears down and rebuilds the widget from scratch – anything drawn outside the render function (mouse strokes, animation frames) is lost, since canvas content is draw commands, not widget state:

examples/11_inplace_vs_rerender.pyexcerpt · 12 of 68 lines
@reactive.effect
def _update_square():
    c = canvas.widget
    if c is not None:
        c.fill_style = input.color()
        c.fill_rect(20, 20, 80, 80)


@reactive.effect
@reactive.event(input.rerender)
def _force_rerender():
    rerender_trigger.set(rerender_trigger() + 1)

The hand-drawn stroke survives the in-place color change but disappears after the forced re-render, while the square’s color is still correctly reapplied. Neither effect above needs reactive.isolate(), since neither reads a value it also writes – add it if you ever .read()/reactive_read() a trait inside the same effect that sets it, to avoid an infinite loop.

Animation loops

Keep frequently-redrawn state (a grid, a particle list) as a plain mutable Python object rather than a reactive.value, and have every writer – a click handler, a button effect, an invalidate_later() tick – redraw the widget directly afterwards. Because .widget stays live after render, an effect can step a simulation and redraw every frame, entirely from Python, with no client-side loop:

examples/05_game_of_life.pyexcerpt · 10 of 54 lines
    @reactive.effect
    def _tick():
        global grid
        reactive.invalidate_later(0.15)
        if not running():
            return
        grid = step(grid)
        c = life.widget
        if c is not None:
            c.put_image_data(grid_to_rgba(grid), 0, 0)

examples/05_game_of_life.py and the Game of Life gallery template both use this shape, keeping the grid outside reactive.value to avoid a feedback loop.

Linking widgets

Table selection highlights the canvas

The reverse direction: a render.DataGrid(selection_mode="row") drives which point gets a highlight ring on the canvas, redrawn in an effect that reads table.cell_selection()["rows"]:

@reactive.effect
def _highlight_selected():
    rows = table.cell_selection()["rows"]
    redraw(rows[0] if rows else None)

Large data

ipycanvas has no large-data mode of its own: it’s a drawing surface, not a data renderer, so there’s no point or row count to scale against. For exploring millions of actual data points rather than drawing shapes, use k3d instead.

Layout and sizing

In a filling layout (the default), the canvas keeps its constructor width/height as the drawing-buffer size and centers itself, shrinking (aspect preserved) if the container is smaller. An explicit @render_ipycanvas(height="150px") opts out of fill but still shrinks-and-centers. Setting widget.layout.height directly also opts out of fill – prefer the constructor or the output’s height= instead, since the buffer size itself is what you’re actually sizing:

examples/15_layout_sizing.pyexcerpt · 3 of 38 lines
@render_ipycanvas(height="150px")
def fixed_height():
    return draw(Canvas(width=300, height=200))

All three paths shrink-and-center with the aspect ratio preserved, rather than stretching the bitmap.

layout and sizing

Gotchas

  • Canvas content is stateless: a browser refresh starts a new session blank, with no built-in undo. Keep your own list of what you’ve drawn if you need either.
  • A reactive.value that’s both read and written inside an invalidate_later() tick keeps re-invalidating itself, and button clicks stop registering. Keep animation-loop state in a plain mutable Python object and redraw the widget directly from each writer (see Updating in place), or read the value inside with reactive.isolate(): so the tick doesn’t depend on it.

Learn more