This commit is contained in:
Thomas Forgione 2022-08-02 14:38:08 +02:00
parent f528fdc1b9
commit df73f99345

View File

@ -15,10 +15,7 @@ use crate::{log, Result};
pub const SPRITE_SIZE: f64 = 32.0; pub const SPRITE_SIZE: f64 = 32.0;
/// A wrapper to make it easier to manage HTML images. /// A wrapper to make it easier to manage HTML images.
pub struct Image { pub struct Image(Rc<RefCell<InnerImage>>);
/// The inner image.
pub inner: Rc<RefCell<InnerImage>>,
}
/// The content of the image. /// The content of the image.
pub struct InnerImage { pub struct InnerImage {
@ -35,14 +32,12 @@ impl Image {
let image = HtmlImageElement::new()?; let image = HtmlImageElement::new()?;
image.set_src(path); image.set_src(path);
let image = Image { let image = Image(Rc::new(RefCell::new(InnerImage {
inner: Rc::new(RefCell::new(InnerImage { inner: image,
inner: image, loaded: false,
loaded: false, })));
})),
};
let clone = image.inner.clone(); let clone = image.0.clone();
let path_clone = path.to_string(); let path_clone = path.to_string();
let cb = Closure::<dyn FnMut(_)>::new(move |_event: web_sys::Event| { let cb = Closure::<dyn FnMut(_)>::new(move |_event: web_sys::Event| {
@ -51,7 +46,7 @@ impl Image {
}); });
image image
.inner .0
.borrow() .borrow()
.inner .inner
.set_onload(Some(cb.as_ref().unchecked_ref())); .set_onload(Some(cb.as_ref().unchecked_ref()));
@ -63,7 +58,7 @@ impl Image {
/// Returns whether the image is loaded. /// Returns whether the image is loaded.
pub fn is_loaded(&self) -> bool { pub fn is_loaded(&self) -> bool {
self.inner.borrow().loaded self.0.borrow().loaded
} }
/// Renders the image on a context. /// Renders the image on a context.
@ -74,7 +69,7 @@ impl Image {
context: &web_sys::CanvasRenderingContext2d, context: &web_sys::CanvasRenderingContext2d,
) -> Result<()> { ) -> Result<()> {
context.draw_image_with_html_image_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh( context.draw_image_with_html_image_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(
&self.inner.borrow().inner, &self.0.borrow().inner,
source.position.x, source.position.x,
source.position.y, source.position.y,
source.size.x, source.size.x,