Skip to main content

Canvas

Struct Canvas 

Source
pub struct Canvas { /* private fields */ }
Expand description

Builder for a single frame’s draw commands. Wraps Painter and adds canvas helpers.

Implementations§

Source§

impl Canvas

Source

pub fn viewport(&self) -> Viewport

Source

pub fn current_transform(&self) -> Transform2D

Get the current transform from the painter’s transform stack.

Source

pub fn clear(&mut self, color: ColorLinPremul)

Set the frame clear/background color (premultiplied linear RGBA).

Source

pub fn fill_rect( &mut self, x: f32, y: f32, w: f32, h: f32, brush: Brush, z: i32, )

Fill a rectangle with a brush.

Source

pub fn external_texture( &mut self, rect: Rect, texture_id: ExternalTextureId, z: i32, )

Composite an externally-rendered texture at the given rectangle.

The texture_id must be registered with the PassManager before the frame is submitted via register_external_texture.

Source

pub fn fill_overlay_rect( &mut self, x: f32, y: f32, w: f32, h: f32, color: ColorLinPremul, )

Fill a rectangle as an overlay (no depth testing). Use this for modal scrims and other overlays that should blend over existing content without blocking text rendered at lower z-indices.

The rectangle coordinates are transformed by the current canvas transform, so they should be in local (viewport) coordinates.

Source

pub fn fill_scrim_rect( &mut self, x: f32, y: f32, w: f32, h: f32, color: ColorLinPremul, )

Fill a rectangle as a scrim (blends over all existing content but allows subsequent z-ordered draws to render on top).

Unlike fill_overlay_rect, this uses a depth buffer attachment with:

  • depth_compare = Always (always passes depth test)
  • depth_write_enabled = false (doesn’t affect depth buffer)

This allows the scrim to dim background content while the modal panel (rendered at a higher z-index afterward) renders cleanly on top.

Source

pub fn fill_scrim_with_cutout( &mut self, hole: RoundedRect, color: ColorLinPremul, )

Fill a fullscreen scrim that leaves a rounded-rect hole using stencil.

Source

pub fn stroke_path( &mut self, path: Path, width: f32, color: ColorLinPremul, z: i32, )

Stroke a path with uniform width and solid color.

Paths that are not fully contained within the active clip are rejected because arbitrary path geometry cannot be CPU-clipped to a rectangle.

Source

pub fn fill_path(&mut self, path: Path, color: ColorLinPremul, z: i32)

Fill a path with a solid color.

Paths that are fully outside the active clip are rejected.

Source

pub fn ellipse( &mut self, center: [f32; 2], radii: [f32; 2], brush: Brush, z: i32, )

Draw an ellipse (y-down coordinates).

Source

pub fn circle(&mut self, center: [f32; 2], radius: f32, brush: Brush, z: i32)

Draw a circle (y-down coordinates).

Source

pub fn rounded_rect(&mut self, rrect: RoundedRect, brush: Brush, z: i32)

Draw a rounded rectangle fill.

Source

pub fn stroke_rounded_rect( &mut self, rrect: RoundedRect, width: f32, brush: Brush, z: i32, )

Stroke a rounded rectangle.

Source

pub fn draw_text_run( &mut self, origin: [f32; 2], text: String, size_px: f32, color: ColorLinPremul, z: i32, )

Draw text using direct rasterization (recommended).

This method rasterizes glyphs immediately using the text provider, bypassing complex display list paths. This is simpler and more reliable than deferred rendering.

§Performance
  • Glyphs are shaped and rasterized on each call
  • Use TextLayoutCache to cache wrapping computations
  • Debounce resize events to avoid excessive rasterization
§Transform Stack

The current transform is applied to position text correctly within zones (viewport, toolbar, etc.).

§DPI Scaling

Both position and size are automatically scaled by self.dpi_scale.

§Example
canvas.draw_text_run(
    [10.0, 20.0],
    "Hello, world!".to_string(),
    16.0,
    ColorLinPremul::rgba(255, 255, 255, 255),
    10,  // z-index
);
Source

pub fn draw_text_run_weighted( &mut self, origin: [f32; 2], text: String, size_px: f32, weight: f32, color: ColorLinPremul, z: i32, )

Draw a text run with an explicit font weight.

weight should follow CSS semantics (100–900; 400 = normal, 700 = bold).

Source

pub fn draw_text_run_styled( &mut self, origin: [f32; 2], text: String, size_px: f32, weight: f32, style: FontStyle, family: Option<String>, color: ColorLinPremul, z: i32, )

Draw a text run with full styling options.

weight should follow CSS semantics (100–900; 400 = normal, 700 = bold). style specifies normal, italic, or oblique rendering. family optionally overrides the font family.

Source

pub fn draw_text_run_gradient( &mut self, origin: [f32; 2], text: String, size_px: f32, weight: f32, style: FontStyle, family: Option<String>, brush: &Brush, text_width: f32, z: i32, )

Draw text with per-glyph gradient color sampling.

Works like draw_text_run_styled but instead of a single flat color, each glyph is tinted by sampling the provided Brush at the glyph’s normalised horizontal position (t = glyph_x / text_width). This implements CSS background-clip: text with gradient backgrounds.

Source

pub fn draw_text_direct( &mut self, origin: [f32; 2], text: &str, size_px: f32, color: ColorLinPremul, provider: &dyn TextProvider, z: i32, )

Draw text directly by rasterizing immediately (simpler, bypasses display list). This is the recommended approach - it’s simpler and more reliable than draw_text_run.

Source

pub fn set_text_provider( &mut self, provider: Arc<dyn TextProvider + Send + Sync>, )

Provide a text provider used for high-level text runs in this frame.

Source

pub fn text_provider(&self) -> Option<&Arc<dyn TextProvider + Send + Sync>>

Source

pub fn measure_text_width(&self, text: &str, size_px: f32) -> f32

Measure the width of a text run in logical pixels using the active text provider.

This is intended for layout/centering code that needs a more accurate width than simple character-count heuristics. When no provider is set, falls back to font_size * 0.55 * text.len() to match legacy behavior.

Source

pub fn measure_text_width_styled( &self, text: &str, size_px: f32, weight: f32, style: FontStyle, family: Option<&str>, ) -> f32

Measure the width of a styled text run in logical pixels.

Unlike measure_text_width, this accounts for font weight, style, and family so that measurements match draw_text_run_styled rendering.

Source

pub fn draw_text_glyphs( &mut self, origin: [f32; 2], glyphs: &[RasterizedGlyph], color: ColorLinPremul, z: i32, )

Draw pre-rasterized glyph masks at the given origin tinted with the color.

Draw a hyperlink with text, optional underline, and URL target.

§Example
let link = Hyperlink {
    text: "Click me".to_string(),
    pos: [10.0, 20.0],
    size: 16.0,
    color: ColorLinPremul::from_srgba_u8([0, 122, 255, 255]),
    url: "https://example.com".to_string(),
    weight: 400.0,
    measured_width: None,
    underline: true,
    underline_color: None,
    family: None,
    style: jag_draw::FontStyle::Normal,
};
canvas.draw_hyperlink(link, 10);
Source

pub fn draw_svg<P: Into<PathBuf>>( &mut self, path: P, origin: [f32; 2], max_size: [f32; 2], z: i32, )

Queue an SVG to be rasterized and drawn at origin, scaled to fit within max_size. Captures the current transform from the painter’s transform stack. Optional style parameter allows overriding fill, stroke, and stroke-width.

Source

pub fn draw_svg_styled<P: Into<PathBuf>>( &mut self, path: P, origin: [f32; 2], max_size: [f32; 2], style: SvgStyle, z: i32, )

Queue an SVG with style overrides to be rasterized and drawn.

Source

pub fn draw_image<P: Into<PathBuf>>( &mut self, path: P, origin: [f32; 2], size: [f32; 2], fit: ImageFitMode, z: i32, )

Queue a raster image (PNG/JPEG/GIF/WebP) to be drawn at origin with the given size. The fit parameter controls how the image is scaled within the size bounds. Captures the current transform from the painter’s transform stack.

Source

pub fn draw_raw_image( &mut self, pixels: Vec<u8>, src_width: u32, src_height: u32, origin: [f32; 2], dst_size: [f32; 2], z: i32, )

Queue raw pixel data to be drawn at origin with the given size. Pixels should be in BGRA format (4 bytes per pixel) to match CEF native output. Captures the current transform from the painter’s transform stack.

Source

pub fn draw_raw_image_with_dirty_rects( &mut self, pixels: Vec<u8>, src_width: u32, src_height: u32, origin: [f32; 2], dst_size: [f32; 2], z: i32, dirty_rects: Vec<(u32, u32, u32, u32)>, )

Queue raw pixel data with dirty rects for partial update. Pixels should be in BGRA format (4 bytes per pixel) to match CEF native output. Only the dirty rectangles will be uploaded to the GPU texture.

Source

pub fn push_clip_rect(&mut self, rect: Rect)

Source

pub fn pop_clip(&mut self)

Source

pub fn push_transform(&mut self, t: Transform2D)

Source

pub fn pop_transform(&mut self)

Source

pub fn push_opacity(&mut self, opacity: f32)

Source

pub fn pop_opacity(&mut self)

Source

pub fn hit_region_rect(&mut self, id: u32, rect: Rect, z: i32)

Add a hit-only region (invisible, used for interaction detection)

Source

pub fn command_count(&self) -> usize

Return the current number of commands in the display list.

Source

pub fn display_list(&self) -> &DisplayList

Get a reference to the display list for hit testing

Source

pub fn snap_rect_logical_to_device(&self, rect: Rect) -> Rect

Snap a rectangle defined in logical coordinates so that, after applying the current transform and DPI scale, its edges land on physical pixel boundaries. This assumes the current transform is an axis-aligned translate/scale (no rotation/skew); for more complex transforms the original rect is returned unchanged.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,