Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set canvas to full size in web? #3140

Closed
RicardoHS opened this issue Oct 13, 2023 · 2 comments
Closed

How to set canvas to full size in web? #3140

RicardoHS opened this issue Oct 13, 2023 · 2 comments

Comments

@RicardoHS
Copy link

I've looking through some issues in the repo but I see no clear way on how to do such thing.

Any instructions on how to proceed?

@daxpedda
Copy link
Member

Winit provides no way to do this.
You can do this on your end by simply setting the size (width and height) of the canvas to 100% with CSS. This is also doable through web-sys.

Eventually Winit will support this when #696 is tackled.

@RicardoHS
Copy link
Author

RicardoHS commented Oct 15, 2023

Thanks for the info. I finally managed to achieve this with some adjustems of #1491

I will leave the code here in case anyone found it helpfull

let window = WindowBuilder::new().build(&event_loop).unwrap();

web_sys::window().and_then(|win| {
    let width = win.inner_width().unwrap().as_f64().unwrap() as u32;
    let height = win.inner_height().unwrap().as_f64().unwrap() as u32;
    let factor = window.scale_factor();
    let logical = LogicalSize { width, height };
    let PhysicalSize { width, height }: PhysicalSize<u32> = logical.to_physical(factor);
    window.set_inner_size(PhysicalSize::new(width, height));
    win.document()
  })
  .and_then(|doc| {
      let dst = doc.get_element_by_id("<your_body_id_in_the_html_doc>")?;
      let canvas = web_sys::Element::from(window.canvas());
      dst.append_child(&canvas).ok()?;
      Some(())
  })
  .expect("Couldn't append canvas to document body.");

And the CSS

* { margin:0; padding:0; } 
html, body { width:100%; height:100%; }
canvas {
    background-color: black;
    display:block;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants