From 43f14444fa6f4756aaac255e9c1b47b756d0ecd5 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Thu, 30 May 2019 00:13:18 +0200 Subject: Initialise WebGl2 context --- WebInterface/wasm/webhogg/src/canvas.rs | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 WebInterface/wasm/webhogg/src/canvas.rs (limited to 'WebInterface/wasm/webhogg/src/canvas.rs') diff --git a/WebInterface/wasm/webhogg/src/canvas.rs b/WebInterface/wasm/webhogg/src/canvas.rs new file mode 100644 index 0000000..a0ef7d1 --- /dev/null +++ b/WebInterface/wasm/webhogg/src/canvas.rs @@ -0,0 +1,42 @@ +use web_sys::WebGl2RenderingContext as WebGl2; +use wasm_bindgen::JsCast; +use crate::webhogg_exception::WebhoggException; +use crate::page::Page; + +pub struct Canvas { + ctx: WebGl2, +} + +impl Canvas { + pub fn from_existing(id: &str, page: &Page) -> Result { + let canvas_element = page.get_element(id) + .ok_or(WebhoggException::DomError( + "could not obtain canvas element (id=canvas)" + .to_string()))?; + let canvas_element = canvas_element + .dyn_into::() + .map_err(|_| WebhoggException::DomError( + "id=canvas is not a canvas element".to_string()))?; + debug!("successfully obtained canvas element"); + let ctx = canvas_element.get_context("webgl2") + .map_err(|_| WebhoggException::WebGlContextError( + "obtained invalid webgl2 context js value".to_string()))? + .ok_or(WebhoggException::WebGlContextError( + "could not obtaine webgl2 context".to_string()))? + .dyn_into::() + .map_err(|_| WebhoggException::WebGlContextError( + "obtained invalid webgl2 context js object".to_string()))?; + debug!("successfully obtained webgl2 context"); + Ok(Self { + ctx, + }) + } + + pub fn gl<'a>(&'a self) -> &'a WebGl2 { + &self.ctx + } + + pub fn gl_mut<'a>(&'a mut self) -> &'a mut WebGl2 { + &mut self.ctx + } +} -- cgit v1.2.3-54-g00ecf