stdweb :: web :: html_element :: canvaselement from document()。query_selector()

发布于 2025-02-07 23:32:18 字数 1844 浏览 2 评论 0 原文

我正在Rust构建紫杉WebApp,并试图从CSS选择器中获得CanvasRenderingContext2D。我存在的问题是如何将 stdweb :: Web :: element 转换为 stdweb :: Web :: HTML_Element :: Canvaselement

我当前的代码是:

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
}

货物检查报告以下错误,

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`

我的最终目标是返回 canvasrenderingContext2d 我假设需要 canvas_element.get_context()

正确的方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

舟遥客 2025-02-14 23:32:18

尝试 dyn_into

  let canvas = document
    .get_element_by_id("my-canvas")
    .unwrap()
    .dyn_into::<web_sys::HtmlCanvasElement>()?;

jscast 文档。

Try dyn_into:

  let canvas = document
    .get_element_by_id("my-canvas")
    .unwrap()
    .dyn_into::<web_sys::HtmlCanvasElement>()?;

More info in the JsCast docs.

一杆小烟枪 2025-02-14 23:32:18

谢谢@Ben在上面的答案中激发了我的启发。

该代码在实践中实现比您的代码Snippit建议更复杂。但是,您的提示使用 .dyn_into()来自 jscast 允许我搜索GitHub以获取更多代码示例。

After a few days of effort, I was finally able to get the following code snippit to compile and render:

  • Inspiration:
use anyhow::{anyhow, Result};
use wasm_bindgen::JsCast;
use web_sys::{CanvasRenderingContext2d, Document, HtmlCanvasElement, Window};

#[allow(dead_code)]
// DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Window
pub fn window() -> Result<Window> {
    web_sys::window()
        .ok_or_else(|| anyhow!("No Window Found"))
}

#[allow(dead_code)]
// DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Document
pub fn document() -> Result<Document> {
    window()?
        .document()
        .ok_or_else(|| anyhow!("No Document Found"))
}

#[allow(dead_code)]
// DOCS: https://developer.mozilla.org/en-US/docs/Web/API/HtmlCanvasElement
pub fn canvas(id_selector: &str) -> Result<HtmlCanvasElement> {
    document()?
        .get_element_by_id(id_selector)
        .ok_or_else(|| anyhow!("No Canvas Element found with ID 'canvas'"))?
        .dyn_into::<web_sys::HtmlCanvasElement>()
        .map_err(|element| anyhow!("Error converting {:#?} to HtmlCanvasElement", element))
}

#[allow(dead_code)]
// DOCS: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2d
pub fn canvas_context_2d(id_selector: &str) -> Result<CanvasRenderingContext2d> {
    canvas(id_selector)?
        .get_context("2d")
        .map_err(|js_value| anyhow!("Error getting 2d context {:#?}", js_value))?
        .ok_or_else(|| anyhow!("No 2d context found"))?
        .dyn_into::<web_sys::CanvasRenderingContext2d>()
        .map_err(|element| {
            anyhow!(
                "Error converting {:#?} to CanvasRenderingContext2d",
                element
            )
        })
}

Thank you @ben for inspiring me with your answer above.

The code was a little more complex to implement in practice than your code snippit suggested. However your hint to use .dyn_into() from JsCast allowed me to search github for more code examples.

After a few days of effort, I was finally able to get the following code snippit to compile and render:

use anyhow::{anyhow, Result};
use wasm_bindgen::JsCast;
use web_sys::{CanvasRenderingContext2d, Document, HtmlCanvasElement, Window};

#[allow(dead_code)]
// DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Window
pub fn window() -> Result<Window> {
    web_sys::window()
        .ok_or_else(|| anyhow!("No Window Found"))
}

#[allow(dead_code)]
// DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Document
pub fn document() -> Result<Document> {
    window()?
        .document()
        .ok_or_else(|| anyhow!("No Document Found"))
}

#[allow(dead_code)]
// DOCS: https://developer.mozilla.org/en-US/docs/Web/API/HtmlCanvasElement
pub fn canvas(id_selector: &str) -> Result<HtmlCanvasElement> {
    document()?
        .get_element_by_id(id_selector)
        .ok_or_else(|| anyhow!("No Canvas Element found with ID 'canvas'"))?
        .dyn_into::<web_sys::HtmlCanvasElement>()
        .map_err(|element| anyhow!("Error converting {:#?} to HtmlCanvasElement", element))
}

#[allow(dead_code)]
// DOCS: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2d
pub fn canvas_context_2d(id_selector: &str) -> Result<CanvasRenderingContext2d> {
    canvas(id_selector)?
        .get_context("2d")
        .map_err(|js_value| anyhow!("Error getting 2d context {:#?}", js_value))?
        .ok_or_else(|| anyhow!("No 2d context found"))?
        .dyn_into::<web_sys::CanvasRenderingContext2d>()
        .map_err(|element| {
            anyhow!(
                "Error converting {:#?} to CanvasRenderingContext2d",
                element
            )
        })
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文