From 4a951c6035814edf8044b43387dbf4be6e1bb119 Mon Sep 17 00:00:00 2001 From: Rob Watson Date: Wed, 9 Sep 2020 11:12:49 +0200 Subject: [PATCH] Small clean up --- src/canvas.rs | 62 ++++++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 33 deletions(-) diff --git a/src/canvas.rs b/src/canvas.rs index 67b5782..1cb17f1 100644 --- a/src/canvas.rs +++ b/src/canvas.rs @@ -69,12 +69,9 @@ impl Canvas { fn redraw_canvas(&mut self) { let canvas_element = self.canvas_node.cast::().unwrap(); - // canvas_element.clear(); TODO - let width = canvas_element.width(); let height = canvas_element.height(); - // TODO: error handling let context = canvas_element .get_context("2d") .unwrap() @@ -84,37 +81,36 @@ impl Canvas { context.set_fill_style(&"black".into()); context.set_stroke_style(&"green".into()); - context.fill_rect(0.0, 0.0, width as f64, height as f64); + context.fill_rect(0.0, 0.0, canvas_element.width() as f64, height as f64); - // TODO: improve - if self.audio_data.is_none() { - return; + if self.audio_data.is_some() { + let audio_data = self.audio_data.as_ref().unwrap(); + + // TODO: multi-channel + let _num_channels = audio_data.number_of_channels(); // 1 + + let channel_data = audio_data.get_channel_data(0).unwrap(); + let chunks = utils::chunks_fixed(&channel_data, canvas_element.width() as usize); + + chunks.enumerate().for_each(|(i, chunk)| { + let max = chunk + .iter() + .map(|v| (v * 32767.0) as i32) + .map(|v| v.abs()) + .max() + .unwrap(); + + let pc = (max as f64 / 32767.0) * 100.0; + let len = (height as f64 / 100.0 * pc).floor(); + let mid = height as f64 / 2f64; + + context.begin_path(); + context.move_to(i as f64, mid - (len / 2f64)); + context.line_to(i as f64, mid + (len / 2f64)); + context.stroke(); + + // ConsoleService::log(&format!("index {}: max {}, pc {}, len {}", i, max, pc, len)); + }); } - let audio_data = self.audio_data.as_ref().unwrap(); - - // TODO: multi-channel - let _num_channels = audio_data.number_of_channels(); // 1 - - let channel_data = audio_data.get_channel_data(0).unwrap(); - let chunks = utils::chunks_fixed(&channel_data, width as usize); - - chunks.enumerate().for_each(|(i, chunk)| { - let max = chunk - .iter() - .map(|v| (v * 32767.0) as i32) - .map(|v| v.abs()) - .max() - .unwrap(); - - let pc = (max as f64 / 32767.0) * 100.0; - let len = (height as f64 / 100.0 * pc).floor(); - let mid = height as f64 / 2f64; - - context.begin_path(); - context.move_to(i as f64, mid - (len / 2f64)); - context.line_to(i as f64, mid + (len / 2f64)); - context.stroke(); - // ConsoleService::log(&format!("index {}: max {}, pc {}, len {}", i, max, pc, len)); - }); } }