From 8333df9474c260de711229e6d3e4cc6f52465dda Mon Sep 17 00:00:00 2001 From: Jean-Marie Mineau Date: Sun, 13 Feb 2022 14:48:00 +0100 Subject: [PATCH] add timer --- index.html | 2 +- src/lib.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/index.html b/index.html index 9d6dbe9..8c1c9bd 100644 --- a/index.html +++ b/index.html @@ -20,7 +20,7 @@ transform: translate(-50%, -50%); } - + diff --git a/src/lib.rs b/src/lib.rs index 8417a2b..f909f25 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,7 @@ use wasm_bindgen::prelude::*; +use std::cell::RefCell; +use std::rc::Rc; +use js_sys::Date; use wasm_bindgen::JsCast; mod drawing; @@ -8,6 +11,15 @@ mod circle; use shapes::*; use circle::CircleShapes; +fn request_animation_frame(f: &Closure) { + web_sys::window() + .unwrap() + .request_animation_frame( + f.as_ref() + .unchecked_ref() + ).unwrap(); +} + #[wasm_bindgen(start)] pub fn start() { let canvas_id = "circle_canvas"; @@ -25,11 +37,36 @@ pub fn start() { .dyn_into::() .unwrap(); - context.begin_path(); - - let iter = CircleShapes::new(100, 13, Circle {center: Point {x: 75.0, y: 75.0}, radius: 70.0}); - for shape in iter { - drawing::draw_shape(shape, &context); - } - context.stroke(); + + let f = Rc::new(RefCell::new(None)); + let g = f.clone(); + + let mut timestamp: Option = None; + let mut factor = 2; + let mut modulo = 10; + + *g.borrow_mut() = Some(Closure::wrap(Box::new(move || { + match timestamp { + Some(date) if (Date::now() - date) < 250. => (), + _ => { + timestamp = Some(Date::now()); + context.begin_path(); + let iter = CircleShapes::new(modulo, factor, Circle {center: Point {x: 400.0, y: 400.0}, radius: 400.0}); + for shape in iter { + drawing::draw_shape(shape, &context); + } + context.stroke(); + + factor += 1; + if factor == modulo { + factor = 2; + modulo += 1; + } + } + } + + request_animation_frame(f.borrow().as_ref().unwrap()); + }) as Box)); + + request_animation_frame(g.borrow().as_ref().unwrap()); }