diff options
author | Joris | 2020-01-28 09:55:58 +0100 |
---|---|---|
committer | Joris | 2020-01-29 10:12:31 +0100 |
commit | 1b6a7e0d00703e3da2e1620b5a2b2cba027161de (patch) | |
tree | 5143f784e1529d3b6c04116c84f09c426bb257b0 /src/canvas.rs | |
parent | 197b6fa7aa810147d63209408c3a378ec552d0f4 (diff) |
Implement game of life
Diffstat (limited to 'src/canvas.rs')
-rw-r--r-- | src/canvas.rs | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/src/canvas.rs b/src/canvas.rs new file mode 100644 index 0000000..38aef4d --- /dev/null +++ b/src/canvas.rs @@ -0,0 +1,64 @@ +use wasm_bindgen::prelude::JsValue; +use wasm_bindgen::JsCast; +use web_sys::CanvasRenderingContext2d; + +pub struct Canvas { + context: CanvasRenderingContext2d, + width: u32, + height: u32, + scaled_width: u32, + scaled_height: u32, +} + +impl Canvas { + pub fn new(attr_id: &str, width: u32, height: u32) -> Canvas { + let document = web_sys::window().unwrap().document().unwrap(); + let canvas = document.get_element_by_id(attr_id).unwrap(); + let canvas: web_sys::HtmlCanvasElement = canvas + .dyn_into::<web_sys::HtmlCanvasElement>() + .unwrap(); + + let context = canvas + .get_context("2d") + .unwrap() + .unwrap() + .dyn_into::<web_sys::CanvasRenderingContext2d>() + .unwrap(); + + let scaled_width = canvas.width() / width; + let scaled_height = canvas.height() / height; + + Canvas { + context, + width, + height, + scaled_width, + scaled_height, + } + } + + pub fn clear(&self) { + self.context.set_fill_style(&JsValue::from_str("white")); + + self.context.fill_rect( + f64::from(0), + f64::from(0), + f64::from(self.width * self.scaled_width), + f64::from(self.height * self.scaled_height) + ); + } + + pub fn draw(&self, x: u32, y: u32, color: &str) { + assert!(x < self.width); + assert!(y < self.height); + + self.context.set_fill_style(&JsValue::from_str(color)); + + self.context.fill_rect( + f64::from(x * self.scaled_width), + f64::from(y * self.scaled_height), + f64::from(self.scaled_width), + f64::from(self.scaled_height) + ); + } +} |