-
Hi everyone, I really want to know if leptos can manipulate H5 Canvas to draw graphics, just like using JS to draw on Canvas.Are there any similar examples? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
Yes. It really has very little to do with Leptos though, and everything to do with the underlying I'd recommend starting with the canvas guides in the |
Beta Was this translation helpful? Give feedback.
-
@xtrn143 Were you able to draw on canvas? Any code samples? |
Beta Was this translation helpful? Give feedback.
-
I guess I was looking for more of a step by step tutorial. Coming from js and some of these things are not obvious. With little bit of luck, I got working as expected.
#[component]
pub fn Spider() -> impl IntoView {
let canvas_ref = create_node_ref::<html::Canvas>();
create_effect(move |_| {
if let Some(canvas) = canvas_ref.get() {
let width = canvas.offset_width() as u32;
let height = canvas.offset_height() as u32;
canvas.set_width(width);
canvas.set_height(height);
let html_canvas = canvas.deref();
let ctx = html_canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<CanvasRenderingContext2d>()
.unwrap();
ctx.set_fill_style(&JsValue::from_str("red"));
ctx.begin_path();
// what ever you want to do with the canvas
ctx.fill();
}
});
view! {
<canvas node_ref=canvas_ref class=styles::canvas />
}
} |
Beta Was this translation helpful? Give feedback.
Yes.
It really has very little to do with Leptos though, and everything to do with the underlying
wasm-bindgen
andweb-sys
crates that power the whole Rust/WASM web ecosystem.I'd recommend starting with the canvas guides in the
wasm-bindgen
docs and going from there. You can easily get access to anHtmlCanvasElement
from a LeptosNodeRef
on a<canvas>
in theview
.