Documentation / Fundamentals

Canvas

Build portable vector illustrations with shapes, paths, reactive canvas inputs, and animation.

Choose a shape or a canvas

Use shape(...) when you need one piece of geometry with a fill or outline. Use canvas(...) for a drawing made of several paths, gradients, clips, or effects. Use canvas_with(...) when the drawing depends on graph-backed state or environment values.

The same Rust drawing code runs on desktop and web. Desktop lowers commands to Vello; web renders retained SVG nodes. Refract's Canvas is a portable view API, not a promise to use an HTML canvas element.

Import refract::prelude::* for the drawing types and constructors. The drawing reference lists each view's construction and specific modifiers; Path documents geometry construction.

Start with a shape

Circle, Ellipse, and Rectangle implement Shape. Pass one to shape(...) to create a view. Shapes start with a black fill and no stroke. Configure fill, no_fill, and stroke before shared modifiers such as width or padding consume the ShapeView builder.

A circle uses the smaller dimension and stays centered. An ellipse or rectangle fills its bounds. Path also implements Shape, but keeps its original coordinates instead of scaling with the bounds.

status_dot.rs
use refract::prelude::*;

fn status_dot() -> impl View {
    shape(Circle)
        .fill(Color::BLUE)
        .width(24.0)
        .height(24.0)
        .label("Active")
}

Draw in logical coordinates

A canvas callback receives a GraphicsContext and CanvasFrame. Record fills and strokes in order; later ink appears over earlier ink. Paths contain straight segments and quadratic or cubic Bézier curves. Path clones share storage until modified.

Allocate space with width and height or the parent layout. Drawing does not provide intrinsic size. view_box(...) fits a fixed coordinate system into that space, centered with its aspect ratio preserved. It does not change layout dimensions.

CanvasFrame.size is the actual content size. bounds is the view box when configured, otherwise the content rectangle at the origin. All canvas ink, including strokes and blur, is clipped to the allocated content box.

triangle_badge.rs
use refract::prelude::*;

fn triangle_badge() -> impl View {
    canvas(|g, _frame| {
        let path = Path::polygon([
            Point::new(50.0, 10.0),
            Point::new(90.0, 90.0),
            Point::new(10.0, 90.0),
        ]);
        g.fill(&path, Color::BLUE);
        g.stroke(&path, Color::WHITE, StrokeStyle::new(2.0));
    })
    .view_box(Rect::new(0.0, 0.0, 100.0, 100.0))
    .width(160.0)
    .height(120.0)
    .label("Triangle")
}

Choose paints and stroke styles

A Color converts into a solid Paint. Paint::linear(start, end, stops) and Paint::radial(center, radius, stops) use local drawing coordinates. Reuse GradientStop values from the existing style API: offsets must be ordered and between zero and one, with at least two stops. Linear endpoints must differ; a radial radius must be positive.

StrokeStyle::new(width) starts with butt caps, miter joins, a miter limit of 4, and no dashes. Use line_cap, line_join, dash, and dash_offset to configure it; miter_limit is a public field. Dash lengths must be finite and nonnegative, and a nonempty pattern needs a positive entry.

fill uses the nonzero winding rule. Use fill_rule(..., FillRule::EvenOdd) for holes defined by alternating crossings. Strokes are centered on the path and do not expand layout. Invalid geometry, paints, and effects produce a drawing error before reaching the backend.

spectrum_line.rs
use refract::prelude::*;

fn spectrum_line() -> impl View {
    canvas(|g, _frame| {
        let paint = Paint::linear(
            Point::new(10.0, 20.0),
            Point::new(190.0, 20.0),
            vec![
                GradientStop::new(0.0, Color::BLUE),
                GradientStop::new(1.0, Color::WHITE),
            ],
        );
        let line = Path::polyline([
            Point::new(10.0, 20.0),
            Point::new(190.0, 20.0),
        ]);
        g.stroke(
            &line,
            paint,
            StrokeStyle::new(3.0)
                .line_cap(LineCap::Round)
                .dash(vec![8.0, 5.0]),
        );
    })
    .width(200.0)
    .height(40.0)
}

Prepare reactive inputs separately

canvas_with(prepare, draw) gives preparation its own mounted dependency boundary. Use inputs.read(&binding), inputs.with(&binding, |value| ...), or inputs.environment::<K>() to produce owned input data. That data must implement Clone + PartialEq + 'static.

Pass the binding into preparation rather than reading it in the parent. The canvas then owns that dependency, and a value change can prepare the drawing without reevaluating the parent. Preparation may be retried or discarded, so it must not start effects or mutate state.

The draw callback receives the committed snapshot, frame geometry, and clock. It has no graph runtime. Resizing and presentation animation can draw again without evaluating the view or rerunning preparation. The host reuses commands while the snapshot, size, and elapsed time remain unchanged.

progress.rs
use refract::prelude::*;

fn progress(level: Binding<f64>) -> impl View {
    canvas_with(
        move |inputs| inputs.read(&level),
        |g, frame, level| {
            let bounds = frame.bounds;
            let fill = Rect::new(
                bounds.x,
                bounds.y,
                bounds.width * level.clamp(0.0, 1.0),
                bounds.height,
            );
            g.fill(&Path::rectangle(fill), Color::BLUE);
        },
    )
    .width(240.0)
    .height(12.0)
}

Animate a change in input

Add animatable_inputs() to interpolate prepared values under existing animation transactions. Use with_animation for the state-changing action, or a value-scoped animation modifier outside the canvas. Application state holds the target immediately; drawing receives presentation samples. Initial rendering is immediate.

f32, f64, Point, Size, Color, and pairs of Animatable values are supported. Colors interpolate in premultiplied sRGB. Springs retain displayed position and velocity when interrupted. You do not need an Animation canvas schedule for input interpolation: the presentation animation already requests frames.

Custom Animatable implementations return a fixed number of finite scalar components and rebuild the input with with_components. Component order and count must remain stable; other fields snap to the target. Clamp values used as widths, radii, or opacity if spring overshoot could make the recorded drawing invalid.

animated_marker.rs
use refract::prelude::*;

fn marker(position: Binding<Point>) -> impl View {
    canvas_with(
        move |inputs| inputs.read(&position),
        |g, _frame, point| {
            g.fill(
                &Path::ellipse(Rect::new(point.x - 6.0, point.y - 6.0, 12.0, 12.0)),
                Color::BLUE,
            );
        },
    )
    .animatable_inputs()
    .width(200.0)
    .height(80.0)
}

fn move_marker(position: Binding<Point>) -> impl View {
    text("Move marker").on_press(move |action| {
        with_animation(action.runtime(), Animation::spring(), |rt| {
            position.set(rt, Point::new(150.0, 40.0));
        });
    })
}

Use a clock for continuous drawing

Use schedule(CanvasSchedule::animation()) for effects driven by time itself, such as light pulses. CanvasFrame.elapsed is accumulated visible time, not wall-clock time. Keep the clock in drawing instead of writing a graph binding every frame.

The schedule pauses while hidden. Web document/intersection observation and native visibility handling exclude hidden time. Reduced-motion preferences make scheduled drawing use time zero and stop continuous frame requests on web and macOS. This does not disable explicit input animations; other native platforms do not yet bridge the preference.

ScheduleBehavior
CanvasSchedule::OnChangeDefault. Draw at time zero when inputs or size change; no continuous frames.
CanvasSchedule::AnimationAdvance visible time and request frames while visible and motion is allowed.
CanvasSchedule::PausedKeep the elapsed phase without requesting continuous frames. Inputs and size can still update; Animation resumes from that phase.
pulse.rs
use refract::prelude::*;

fn pulse() -> impl View {
    canvas(|g, frame| {
        let center = frame.bounds.center();
        let radius = 12.0 + 4.0 * frame.elapsed.as_secs_f64().sin();
        g.fill(
            &Path::ellipse(Rect::new(
                center.x - radius, center.y - radius,
                radius * 2.0, radius * 2.0,
            )),
            Color::BLUE,
        );
    })
    .schedule(CanvasSchedule::animation())
    .width(80.0)
    .height(80.0)
}

Scope transforms, clips, and effects

GraphicsContext::transformed(matrix, draw) applies an Affine2d to its child commands. clipped(path, rule, draw) restricts their coverage. scoped(draw) groups commands without introducing an isolated effect layer. These operations stay inside the drawing and do not create layout boxes or event targets.

layer(Layer, draw) isolates children, blurs them, applies an optional alpha mask, then composites with group opacity and blend mode. Layer::blur(sigma) uses a Gaussian standard deviation in local logical pixels. A Mask combines a path and paint; only paint alpha affects coverage. The modes are Normal, Multiply, Screen, and Plus.

Keep effect bounds small. A cached drawing avoids regenerating commands, but active animation and large blurred layers still require rendering work. Canvas effects never enlarge layout, hit testing, or the content clip.

soft_light.rs
use refract::prelude::*;

fn soft_light() -> impl View {
    canvas(|g, frame| {
        let fade = Paint::linear(
            Point::new(0.0, 0.0),
            Point::new(frame.bounds.width, 0.0),
            vec![
                GradientStop::new(0.0, Color::WHITE),
                GradientStop::new(1.0, Color(255, 255, 255, 0)),
            ],
        );
        let mask = Mask::new(Path::rectangle(frame.bounds), fade);
        g.layer(Layer::new().blur(4.0).opacity(0.7).mask(mask), |g| {
            g.fill(
                &Path::ellipse(Rect::new(20.0, 20.0, 80.0, 40.0)),
                Color::BLUE,
            );
        });
    })
    .width(160.0)
    .height(80.0)
}

Define reusable geometry

Implement Shape when the same geometry should be filled or stroked in different views. path receives the available bounds; derive coordinates from those bounds to adapt to size changes. For fixed artwork, a stored Path with canvas.view_box is often simpler.

custom_shape.rs
use refract::prelude::*;

struct Triangle;

impl Shape for Triangle {
    fn path(&self, bounds: Rect) -> Path {
        Path::polygon([
            bounds.top_center(),
            bounds.bottom_right(),
            bounds.bottom_left(),
        ])
    }
}

fn triangle() -> impl View {
    shape(Triangle)
        .fill(Color::BLUE)
        .width(80.0)
        .height(60.0)
}

Handle input on the canvas

Attach on_pointer to the canvas and use ActionContext::local_position(event.position) and local_bounds() for the current handler's border-box coordinates. Host geometry accounts for displayed transforms and scrolling. Both methods return Option; an unavailable layout or non-invertible transform can prevent conversion.

Local pointer coordinates are not view-box coordinates. When using view_box, subtract border and padding, then invert the centered aspect-fit drawing transform before testing paths. Drawing commands do not have individual handlers or accessibility nodes; add a label to meaningful artwork and use separate views for separate controls. See Input & Focus.

Prerender the first frame

Canvas participates in web prerendering. The renderer calls drawing with the initial input snapshot and elapsed time zero, emitting SVG paths, gradients, masks, and filters. No browser APIs or mounted effects are available during this work. Give the canvas deterministic initial inputs and explicit dimensions or a view box.

The current prerenderer does not run browser layout: it uses explicit width and height, then view-box dimensions, then a 300 by 150 fallback. Hydration measures the live content size and redraws as needed, so responsive drawings can change after startup.

For an application using build --prerender, export the initial view with refract_web::export_prerender!(application()) and start the browser with refract_web::hydrate using matching options. Matching SVG nodes can be reused, then event handlers and animation become active. Without JavaScript, the initial drawing stays visible. See build output.

Try the animated prism

The canvas example shares an illustration between desktop and web. It combines perspective geometry, spring-driven pointer tilt, gradient fills, alpha masks, blurred light, and scheduled pulses. Pause the pulses, toggle glow, and move the pointer over the prism.

The example's drawing is compatible with prerendering, but its current browser entry uses mount and has no prerender export. Add the export and use hydrate before building that example with --prerender.

Terminal · repository root
refract dev -p refract-canvas --open
# Or run the native app:
refract dev -p refract-canvas --platform desktop