-
In 0.6.x, I was able to create a canvas, get its rendering context and draw, like so (as mentioned in #2245 (reply in thread)): fn prerender_image() -> HtmlElement<Canvas> {
let canvas = html::canvas();
canvas.set_width(64);
canvas.set_height(64);
let ctx = canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<CanvasRenderingContext2d>()
.unwrap();
// Draw image using ctx
canvas
} How do I do this in 0.7.x? Thanks! |
Beta Was this translation helpful? Give feedback.
Answered by
gbj
Jan 17, 2025
Replies: 1 comment 1 reply
-
The new approach doesn't work as well with this kind of imperative style, it's true. It now separates "calling some view functions" from "building actual DOM elements" with an additional There are two decent ways to do it:
fn prerender_image() -> HtmlCanvasElement {
use wasm_bindgen::JsCast;
use web_sys::HtmlCanvasElement;
let canvas = html::canvas().build();
let canvas = canvas.unchecked_into::<HtmlCanvasElement>();
canvas.set_width(64);
canvas.set_height(64);
let ctx = canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<CanvasRenderingContext2d>()
.unwrap();
// Draw image using ctx
canvas
}
fn prerender_image() -> impl IntoView {
let node_ref = NodeRef::new();
let canvas = html::canvas().node_ref(node_ref);
Effect::new(move || {
if let Some(canvas) = node_ref.get() {
canvas.set_width(64);
canvas.set_height(64);
let ctx = canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<CanvasRenderingContext2d>()
.unwrap();
// Draw image using ctx
}
});
canvas
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
janikarki
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The new approach doesn't work as well with this kind of imperative style, it's true. It now separates "calling some view functions" from "building actual DOM elements" with an additional
.build()
method.There are two decent ways to do it:
web-sys
HtmlCanvasElement
. (You won't be able to use this directly in the view, but you can mount it somewhere using web-sys)