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
|
use wasm_bindgen::prelude::JsValue;
use wasm_bindgen::JsCast;
use web_sys::CanvasRenderingContext2d;
pub struct Canvas {
context: CanvasRenderingContext2d,
width: u32,
height: u32,
scaled_width: u32,
scaled_height: u32,
}
impl Canvas {
pub fn new(attr_id: &str, width: u32, height: u32) -> Canvas {
let document = web_sys::window().unwrap().document().unwrap();
let canvas = document.get_element_by_id(attr_id).unwrap();
let canvas: web_sys::HtmlCanvasElement = canvas
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
let context = canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<web_sys::CanvasRenderingContext2d>()
.unwrap();
let scaled_width = canvas.width() / width;
let scaled_height = canvas.height() / height;
Canvas {
context,
width,
height,
scaled_width,
scaled_height,
}
}
pub fn clear(&self) {
self.context.set_fill_style(&JsValue::from_str("white"));
self.context.fill_rect(
f64::from(0),
f64::from(0),
f64::from(self.width * self.scaled_width),
f64::from(self.height * self.scaled_height)
);
}
pub fn draw(&self, x: u32, y: u32, color: &str) {
assert!(x < self.width);
assert!(y < self.height);
self.context.set_fill_style(&JsValue::from_str(color));
self.context.fill_rect(
f64::from(x * self.scaled_width),
f64::from(y * self.scaled_height),
f64::from(self.scaled_width),
f64::from(self.scaled_height)
);
}
}
|