1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use super::drawable::Drawable;
use super::color::Color;
use super::image::Image;
use wasm_bindgen::{JsCast, JsValue};

/// A Canvas is an object on which you can draw.
/// Only the main Canvas is displayed (returned by Window::init()).
/// 
/// # Example
/// 
/// ```rust
/// use wasm_game_lib::graphics::window::Window;
/// use wasm_game_lib::graphics::image::Image;
/// use wasm_game_lib::graphics::sprite::Sprite;
/// use wasm_game_lib::system::sleep;
/// use std::time::Duration;
/// 
/// # async fn test() {
/// // Create a sprite to demonstrate how to draw a sprite on the canvas
/// let texture = Image::load("https://www.gravatar.com/avatar/419218774d04a581476ea1887a0921e0?s=128&d=identicon&r=PG").await.unwrap();
/// let sprite = Sprite::<u32>::new((0,0), &texture, (150, 150));
/// 
/// // create the main canvas
/// let (window, mut canvas) = Window::init(); 
/// 
/// loop {
///     canvas.clear();         // clear the canvas at each iteration
///     canvas.draw(&sprite);   // draw a sprite on the canvas
///     // note that canvas.display() is not needed unlike a lot of graphics libraries
///     
///     // you may want to slow down the loop to keep your game at 60fps
///     sleep(Duration::from_millis(16)).await; 
/// }
/// # }
/// ```
pub struct Canvas {
    pub context: web_sys::CanvasRenderingContext2d,
    pub(crate) element: web_sys::HtmlCanvasElement
}

impl Default for Canvas {
    fn default() -> Self {
        Self::new()
    }
}

impl Canvas {
    /// Create a canvas which will not be displayed.
    /// To create a displayed canvas, see [Window::init()](../window/struct.Window.html#method.init).
    /// Creating a undisplayed canvas can be useful because a canvas is drawable on another canvas.
    pub fn new() -> Canvas {
        let document = web_sys::window().unwrap().document().unwrap();
        let element = document
            .create_element("canvas")
            .unwrap()
            .dyn_into::<web_sys::HtmlCanvasElement>()
            .unwrap();

        let context = element
            .get_context("2d")
            .unwrap()
            .unwrap()
            .dyn_into::<web_sys::CanvasRenderingContext2d>()
            .unwrap();

        Canvas {
            context,
            element
        }
    }

    /// Clear a part of the canvas.
    pub fn clear_rect(&mut self, (x, y): (f64, f64), (w, h): (f64, f64)) {
        self.context.clear_rect(x, y, w, h);
    }

    /// Clear all the canvas with a transparent black (white).
    pub fn clear(&mut self) {
        self.clear_rect(
            (0.0, 0.0),
            (
                f64::from(self.element.width()),
                f64::from(self.element.height()),
            ),
        )
    }

    /// Clear all the canvas with a visible black.
    pub fn clear_with_black(&mut self) {
        self.fill_rect(
            (0.0, 0.0),
            (
                f64::from(self.element.width()),
                f64::from(self.element.height()),
            ),
            Color::black()
        );
    }

    /// Clear all the canvas with a [Color](../color/struct.Color.html).
    pub fn clear_with_color(&mut self, color: Color) {
        self.fill_rect(
            (0.0, 0.0),
            (
                f64::from(self.element.width()),
                f64::from(self.element.height()),
            ),
            color
        );
    }

    /// Draw an object implementing the [Drawable trait](../drawable/trait.Drawable.html) on the canvas.
    /// 
    /// # Example
    /// 
    /// ```rust
    /// # use wasm_game_lib::graphics::window::Window;
    /// # use wasm_game_lib::graphics::image::Image;
    /// # use wasm_game_lib::graphics::sprite::Sprite;
    /// # use wasm_game_lib::system::sleep;
    /// # use std::time::Duration;
    /// # async fn test() {
    /// // create a sprite to draw it on the canvas
    /// let texture = Image::load("https://www.gravatar.com/avatar/419218774d04a581476ea1887a0921e0?s=128&d=identicon&r=PG").await.unwrap();
    /// let sprite = Sprite::<u32>::new((0,0), &texture, (150, 150));
    /// 
    /// // create the main canvas
    /// let (window, mut canvas) = Window::init(); 
    /// 
    /// // draw the sprite on the canvas
    /// canvas.draw(&sprite);
    /// # }
    /// ```
    /// 
    /// See above for a more complete example.
    pub fn draw(&mut self, object: &impl Drawable) {
        object.draw_on_canvas(self);
    }

    /// Draw an image at a specific position.
    /// This method is intended to be used inside the [Drawable trait](../drawable/trait.Drawable.html).
    /// In the main code of your game, you should use a [Sprite](../sprite/struct.Sprite.html) and the [draw](#method.draw) method.
    pub fn draw_image(&mut self, (x, y): (f64, f64), image: &Image) {
        self.context
            .draw_image_with_html_image_element(
                image.get_html_element(),
                x,
                y,
            )
            .unwrap();
    }

    /// Draw a canvas at a specific position.
    pub fn draw_canvas(&mut self, (x, y): (f64, f64), canvas: &Canvas) {
        self.context
            .draw_image_with_html_canvas_element(
                &canvas.element,
                x,
                y,
            )
            .unwrap();
    }

    /// You can use the canvas rendering context to make advanced drawing
    pub fn get_2d_canvas_rendering_context(&mut self) -> &mut web_sys::CanvasRenderingContext2d {
        &mut self.context
    }

    /// You can use the html element to do advanced things
    pub fn get_canvas_element(&self) -> &web_sys::HtmlCanvasElement {
        &self.element
    }

    /// Fill a part of the canvas with a [Color](../color/struct.Color.html).
    pub fn fill_rect(&mut self, (x, y): (f64, f64), (w, h): (f64, f64), color: Color) {
        self.context.set_fill_style(&JsValue::from_str(&color.to_string()));
        self.context.fill_rect(x, y, w, h);
    }

    /// Print text on the canvas.
    /// The [Text](../text/struct.Text.html) struct is a better way to print text.
    pub fn fill_text(&mut self, (x, y): (usize, usize), text: &str, max_width: Option<usize>) {
        if let Some(max_width) = max_width {
            self.context.fill_text_with_max_width(text, x as f64, y as f64, max_width as f64).unwrap();
        } else {
            self.context.fill_text(text, x as f64, y as f64).unwrap();
        }
    }
    
    /// Set the canvas width in pixels
    pub fn set_width(&mut self, width: u32) {
        self.element.set_width(width);
    }

    /// Set the canvas height in pixels
    pub fn set_height(&mut self, height: u32) {
        self.element.set_height(height);
    }

    /// Return the actual canvas width in pixels
    pub fn get_width(&self) -> u32 {
        self.element.width()
    }

    /// Return the actual canvas height in pixels
    pub fn get_height(&self) -> u32 {
        self.element.height()
    }

    /// Return the width and the height of a canvas.
    pub fn get_size(&self) -> (u32, u32) {
        (self.element.width(), self.element.height())
    }
}

/// An enum representing a [lineCap mode](https://developer.mozilla.org/fr/docs/Web/API/CanvasRenderingContext2D/lineCap).
/// You may want to use [LineStyle](struct.LineStyle.html) for a complete set of options.
/// 
/// # Example
/// 
/// ![line cap demonstration](https://media.prod.mdn.mozit.cloud/attachments/2012/07/09/236/50366ad18b04b40276d6ef95d76281b1/Canvas_linecap.png)
pub enum LineCap {
    /// The first line of the example above
    Butt,
    /// The second line of the example above
    Round,
    /// The third line of the example above
    Square
}

impl ToString for LineCap {
    fn to_string(&self) -> String {
        match self {
            LineCap::Butt => String::from("butt"),
            LineCap::Round => String::from("round"),
            LineCap::Square => String::from("square"),
        }
    }
}

/// An enum representing the [lineJoin mode](https://developer.mozilla.org/fr/docs/Web/API/CanvasRenderingContext2D/lineJoin).
/// You may want to use [LineStyle](struct.LineStyle.html) for a complete set of options.
/// 
/// # Example
/// 
/// ![line join demonstration](https://media.prod.mdn.mozit.cloud/attachments/2012/07/09/237/2b7a14b3921934ae35486afd6ba6704a/Canvas_linejoin.png)
pub enum LineJoin {
    /// The first line of the example above
    Round,
    /// The second line of the example above
    Bevel,
    /// The third line of the example above
    Miter,
}

impl ToString for LineJoin {
    fn to_string(&self) -> String {
        match self {
            LineJoin::Miter => String::from("miter"),
            LineJoin::Round => String::from("round"),
            LineJoin::Bevel => String::from("bevel"),
        }
    }
}

/// A struct containing every line option.
pub struct LineStyle {
    /// The color of the line
    pub color: Color,
    /// The width of the line in pixels
    pub size: f64,
    /// The lineCap mode
    pub cap: LineCap,
    /// The lineJoin mode
    pub join: LineJoin
}

impl LineStyle {
    /// Apply these properties on a canvas
    pub fn apply_on_canvas(&self, canvas: &mut Canvas) {
        canvas.context.set_line_width(self.size);
        canvas.context.set_stroke_style(&JsValue::from_str(&self.color.to_string()));
        canvas.context.set_line_cap(&self.cap.to_string());
        canvas.context.set_line_join(&self.join.to_string());
    }
}

impl Default for LineStyle {
    fn default() -> LineStyle {
        LineStyle {
            color: Color::black(),
            size: 3.0,
            cap: LineCap::Butt,
            join: LineJoin::Miter
        }
    }
}