Simon Gardling 544989e4b2 clippy
2022-02-14 09:58:43 -05:00

59 lines
1.4 KiB
Rust

use wasm_bindgen::prelude::*;
use web_sys::HtmlCanvasElement;
mod func_plot;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
pub type DrawResult<T> = Result<T, Box<dyn std::error::Error>>;
/// Result of screen to chart coordinates conversion.
#[wasm_bindgen]
pub struct Point {
pub x: f32,
pub y: f32,
}
#[wasm_bindgen]
impl Point {
pub fn new(x: f32, y: f32) -> Self { Self { x, y } }
}
#[wasm_bindgen]
pub struct Chart {
convert: Box<dyn Fn((i32, i32)) -> Option<(f32, f32)>>,
area: f32,
}
#[wasm_bindgen]
impl Chart {
pub fn draw(
canvas: HtmlCanvasElement, func_str: &str, min_x: f32, max_x: f32, min_y: f32, max_y: f32,
num_interval: usize, resolution: i32,
) -> Result<Chart, JsValue> {
let draw_output = func_plot::draw(
canvas,
func_str,
min_x,
max_x,
min_y,
max_y,
num_interval,
resolution,
)
.map_err(|err| err.to_string())?;
let map_coord = draw_output.0;
Ok(Chart {
convert: Box::new(move |coord| map_coord(coord).map(|(x, y)| (x, y))),
area: draw_output.1,
})
}
pub fn get_area(&self) -> f32 { self.area }
pub fn coord(&self, x: i32, y: i32) -> Option<Point> {
(self.convert)((x, y)).map(|(x, y)| Point::new(x, y))
}
}