~luyu/comp5411-rendering-project

359b9d64427209b59bbb16adc8682febb6d8f4b0 — Luyu Cheng 2 months ago 2250aac
feat: scale canvas by `devicePixelRatio`
2 files changed, 12 insertions(+), 1 deletions(-)

M Cargo.toml
M src/lib.rs
M Cargo.toml => Cargo.toml +3 -0
@@ 23,4 23,7 @@ features = [
  'WebGlProgram',
  'WebGlShader',
  'Window',
  'CssStyleDeclaration',
  'HtmlElement',
  'console',
]

M src/lib.rs => src/lib.rs +9 -1
@@ 4,10 4,18 @@ use web_sys::{WebGl2RenderingContext, WebGlProgram, WebGlShader};

#[wasm_bindgen(start)]
pub fn start() -> Result<(), JsValue> {
    let document = web_sys::window().unwrap().document().unwrap();
    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().unwrap();
    let canvas = document.get_element_by_id("canvas").unwrap();
    let canvas: web_sys::HtmlCanvasElement = canvas.dyn_into::<web_sys::HtmlCanvasElement>()?;

    let device_pixel_ratio = window.device_pixel_ratio();
    let (width, height) = (canvas.width(), canvas.height());
    canvas.style().set_property("width", &format!("{}px", width))?;
    canvas.style().set_property("height", &format!("{}px", height))?;
    canvas.set_width((width as f64 * device_pixel_ratio) as u32);
    canvas.set_height((height as f64 * device_pixel_ratio) as u32);

    let context = canvas
        .get_context("webgl2")?
        .unwrap()