MCPcopy Create free account
hub / github.com/Apress/practical-rust-web-projects / update

Method update

Ch06/yew-image-processing/src/app.rs:31–100  ·  view source on GitHub ↗
(&mut self, msg: Self::Message)

Source from the content-addressed store, hash-verified

29 }
30
31 fn update(&mut self, msg: Self::Message) -> ShouldRender {
32 match msg {
33 Msg::LoadFile(files) => {
34 let file = &files[0];
35 let file_url = web_sys::Url::create_object_url_with_blob(&file).unwrap();
36 let document = web_sys::window().unwrap().document().unwrap();
37 let image = Rc::new(document
38 .create_element("img").unwrap()
39 .dyn_into::<web_sys::HtmlImageElement>().unwrap()
40 );
41 image.set_src(&file_url);
42
43
44 let image_clone = image.clone();
45
46 let callback = Closure::wrap(Box::new(move || {
47 let canvas = document.get_element_by_id("preview").unwrap();
48 let canvas: web_sys::HtmlCanvasElement = canvas
49 .dyn_into::<web_sys::HtmlCanvasElement>()
50 .map_err(|_| ())
51 .unwrap();
52
53 let context = canvas
54 .get_context("2d")
55 .unwrap()
56 .unwrap()
57 .dyn_into::<web_sys::CanvasRenderingContext2d>()
58 .unwrap();
59 canvas.set_width(image_clone.natural_width());
60 canvas.set_height(image_clone.natural_height());
61 context.draw_image_with_html_image_element(&image_clone, 0.0, 0.0).unwrap();
62 }) as Box<dyn Fn()>);
63 // .as_ref().unchecked_ref() can extract the &Function from the &JsValue
64 image.set_onload(Some(callback.as_ref().unchecked_ref()));
65 // Do not drop the Closure so the JS callback won't be invalidated after the
66 // function exits
67 callback.forget();
68 }
69 Msg::Shrink => {
70 // DO nothing yet
71 let document = web_sys::window().unwrap().document().unwrap();
72 let canvas = document.get_element_by_id("preview").unwrap();
73 let canvas: web_sys::HtmlCanvasElement = canvas
74 .dyn_into::<web_sys::HtmlCanvasElement>()
75 .map_err(|_| ())
76 .unwrap();
77
78 let context = canvas
79 .get_context("2d")
80 .unwrap()
81 .unwrap()
82 .dyn_into::<web_sys::CanvasRenderingContext2d>()
83 .unwrap();
84 let width: u32 = canvas.width();
85 let height: u32 = canvas.height();
86 let image_buffer = context.get_image_data(0.0, 0.0, width.into(), height.into())
87 .unwrap()
88 .data();

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected