summaryrefslogtreecommitdiff
path: root/WebInterface/wasm/asm-paint/src/canvas.rs
blob: 400e258dc6cd1ddedaf08a3bf20d8aa9b40c24a7 (plain)
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
use web_sys;
use web_sys::{WebGl2RenderingContext};
use wasm_bindgen::JsCast;
use crate::shader::Shaders;

pub struct Canvas {
    element: web_sys::HtmlCanvasElement,
    ctx: WebGl2RenderingContext,
    shaders: Shaders,
}

impl Canvas {
    pub fn new(element: web_sys::Element) -> Option<Self> {
        let element: web_sys::HtmlCanvasElement =
            element.dyn_into::<web_sys::HtmlCanvasElement>()
            .ok()?;
        debug!("create webgl2 context");
        let ctx = element.get_context("webgl2").ok()??
            .dyn_into::<WebGl2RenderingContext>().ok()?;
        info!("created webgl2 context successfully");
        Some(Self {
            element, ctx,
            shaders: Shaders::new(),
        })
    }

    pub fn init(&mut self) -> Result<(), ()> {
        self.shaders.init(&self.ctx).map_err(|_|())?;
        self.ctx.clear_color(1.0, 0.2, 1.0, 1.0);
        self.ctx.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
        Ok(())
    }
}

impl Drop for Canvas {
    fn drop(&mut self) {
        self.shaders.remove(&self.ctx);
    }
}