Crate wcanvas

source ·
Expand description

wcanvas

This is a 2D graphics library for Rust, on top of winit. It is currently implemented using WebGPU under the hood.

Getting started

The winit crate provides an API for manipulating windows in a cross-platform manner, but intentionally does not support creating any graphics contexts. This is because users might want to use various graphics APIs, such as OpenGL or WebGPU, and they are a separate concern to window creation and manipulation.

wcanvas is a crate which interfaces with winit, and provides a 2D graphics context. You can start by creating an event loop and a window:

#[tokio::main]
async fn main() {
    let event_loop = EventLoop::new();
    let window = WindowBuilder::new()
        .with_title("wcanvas - Getting started")
        .with_inner_size(LogicalSize::new(600, 600))
        .build(&event_loop)
        .unwrap();
 
    // ...
}

Next, a “canvas” for the window needs to be created. This canvas takes ownership of the window, which you can later borrow using the window() method.

use wcanvas::canvas::CanvasBackend;
let mut canvas = window.create_canvas().await.unwrap();

Finally, we will run the event loop, and pick up redraw events:

event_loop.run(move |event, _, control_flow| {
    *control_flow = ControlFlow::Wait;
 
    match event {
        Event::RedrawRequested(window_id) if window_id == canvas.window().id() => {
            // Redraw requested! We will draw here...
        }
    }
});

Finally, we can handle the redraw request by calling the canvas.draw_frame() method. This method takes in a callback, to which it passes the “graphics context”. This graphics context then allows us to draw. For example, we can draw a green square:

canvas.draw_frame(|context| {
    context.set_brush(&Brush::solid(&(0, 255, 0).into()));      // color = green
    context.fill_rect(&(20, 20, 200, 200).into());              // at (20, 20), size 200x200
});

Modules