wasm_game_lib/graphics/
shape.rs

1use super::drawable::Drawable;
2use super::color::Color;
3use super::canvas::*;
4use wasm_bindgen::JsValue;
5
6/// A drawable rectangle
7pub struct Rectangle {
8    /// the [style](../canvas/struct.LineStyle.html) of the border
9    pub line_style: LineStyle,
10    /// point y and point y (in pixels)
11    pub top_left: (f64, f64),
12    /// width and height (in pixels)
13    pub dimensions: (f64, f64),
14    /// if some, the square will be filled by this color
15    pub fill_color: Option<Color>
16}
17
18impl Rectangle {
19    /// Create a rectangle from the top left and the bottom right point
20    pub fn new_with_two_points(point_a: (f64, f64), point_b: (f64, f64)) -> Rectangle {
21        Rectangle {
22            line_style: LineStyle::default(),
23            top_left: point_a,
24            dimensions: (point_b.0 - point_a.0, point_b.1 - point_a.1),
25            fill_color: None
26        }
27    }
28
29    /// Create a rectangle from the top left point and a dimension
30    pub fn new_with_dimension(point: (f64, f64), dimensions: (f64, f64)) -> Rectangle {
31        Rectangle {
32            line_style: LineStyle::default(),
33            top_left: point,
34            dimensions,
35            fill_color: None
36        }
37    }
38}
39
40impl Drawable for Rectangle {
41    fn draw_on_canvas(&self, mut canvas: &mut Canvas) {
42        canvas.context.begin_path();
43        canvas.context.rect(self.top_left.0, self.top_left.1, self.dimensions.0, self.dimensions.1);
44        if let Some(color) = &self.fill_color {
45            canvas.context.set_fill_style(&JsValue::from_str(&color.to_string()));
46            canvas.context.fill();
47        }
48        self.line_style.apply_on_canvas(&mut canvas);
49        canvas.context.stroke();
50    }
51}
52
53/// A simple drawable line
54pub struct Line {
55    /// the [style](../canvas/struct.LineStyle.html) of the line
56    pub line_style: LineStyle,
57    #[allow(missing_docs)]
58    pub point_a: (f64, f64),
59    #[allow(missing_docs)]
60    pub point_b: (f64, f64)
61}
62
63impl Line {
64    /// Create a line with a [default style](../canvas/struct.LineStyle.html#method.default)
65    pub fn new(point_a: (f64, f64), point_b: (f64, f64)) -> Line {
66        Line {
67            line_style: LineStyle::default(),
68            point_a,
69            point_b
70        }
71    }
72}
73
74impl Drawable for Line {
75    fn draw_on_canvas(&self, mut canvas: &mut Canvas) {
76        canvas.context.begin_path();
77        canvas.context.move_to(self.point_a.0, self.point_a.1);
78        canvas.context.line_to(self.point_b.0, self.point_b.1);
79        self.line_style.apply_on_canvas(&mut canvas);
80        canvas.context.stroke();
81    }
82}