stdweb :: web :: html_element :: canvaselement from document()。query_selector()
我正在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()
正确的方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
dyn_into
:jscast 文档。
Try
dyn_into
:More info in the
JsCast
docs.谢谢@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:
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: