I am building a Yew webapp in Rust, and attempting to get a CanvasRenderingContext2d from a CSS selector. The issue I am having is how to convert a stdweb::web::Element
into a stdweb::web::html_element::CanvasElement
.
My current code is this:
use stdweb::web::{CanvasRenderingContext2d, document, Element, IParentNode};
use stdweb::web::html_element::CanvasElement;
fn get_canvas_context(selector: &str) -> CanvasRenderingContext2d {
let element: Element = document().query_selector(selector)
.expect(format!("query_selector({selector}) not found").as_str())
.unwrap()
;
// BUG: the trait `From<stdweb::web::Element>` is not implemented for `CanvasElement`
let canvas_element: CanvasElement = element
.try_into()
.expect(format!("query_selector({selector}) not CanvasElement").as_str())
;
let context: CanvasRenderingContext2d = canvas_element.get_context()
.expect(format!("query_selector({selector}) failed to get_context()").as_str())
;
context
}
cargo check
reports the following error
error[E0277]: the trait bound `CanvasElement: From<stdweb::web::Element>` is not satisfied
--> src/utils.rs:12:10
|
12 | .try_into()
| ^^^^^^^^ the trait `From<stdweb::web::Element>` is not implemented for `CanvasElement`
|
= note: required because of the requirements on the impl of `Into<CanvasElement>` for `stdweb::web::Element`
= note: required because of the requirements on the impl of `std::convert::TryFrom<stdweb::web::Element>` for `CanvasElement`
= note: required because of the requirements on the impl of `std::convert::TryInto<CanvasElement>` for `stdweb::web::Element`
My ultimate goal is to return a CanvasRenderingContext2d
which I assume requires canvas_element.get_context()
What is the correct way to do this?
Try dyn_into
:
let canvas = document
.get_element_by_id("my-canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()?;
More info in the JsCast
docs.