-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Optionally resize Window canvas element to fit parent element (#4726)
Currently Bevy's web canvases are "fixed size". They are manually set to specific dimensions. This might be fine for some games and website layouts, but for sites with flexible layouts, or games that want to "fill" the browser window, Bevy doesn't provide the tools needed to make this easy out of the box. There are third party plugins like [bevy-web-resizer](https://github.com/frewsxcv/bevy-web-resizer/) that listen for window resizes, take the new dimensions, and resize the winit window accordingly. However this only covers a subset of cases and this is common enough functionality that it should be baked into Bevy. A significant motivating use case here is the [Bevy WASM Examples page](https://bevyengine.org/examples/). This scales the canvas to fit smaller windows (such as mobile). But this approach both breaks winit's mouse events and removes pixel-perfect rendering (which means we might be rendering too many or too few pixels). bevyengine/bevy-website#371 In an ideal world, winit would support this behavior out of the box. But unfortunately that seems blocked for now: rust-windowing/winit#2074. And it builds on the ResizeObserver api, which isn't supported in all browsers yet (and is only supported in very new versions of the popular browsers). While we wait for a complete winit solution, I've added a `fit_canvas_to_parent` option to WindowDescriptor / Window, which when enabled will listen for window resizes and resize the Bevy canvas/window to fit its parent element. This enables users to scale bevy canvases using arbitrary CSS, by "inheriting" their parents' size. Note that the wrapper element _is_ required because winit overrides the canvas sizing with absolute values on each resize. There is one limitation worth calling out here: while the majority of canvas resizes will be triggered by window resizes, modifying element layout at runtime (css animations, javascript-driven element changes, dev-tool-injected changes, etc) will not be detected here. I'm not aware of a good / efficient event-driven way to do this outside of the ResizeObserver api. In practice, window-resize-driven canvas resizing should cover the majority of use cases. Users that want to actively poll for element resizes can just do that (or we can build another feature and let people choose based on their specific needs). I also took the chance to make a couple of minor tweaks: * Made the `canvas` window setting available on all platforms. Users shouldn't need to deal with cargo feature selection to support web scenarios. We can just ignore the value on non-web platforms. I added documentation that explains this. * Removed the redundant "initial create windows" handler. With the addition of the code in this pr, the code duplication was untenable. This enables a number of patterns: ## Easy "fullscreen window" mode for the default canvas The "parent element" defaults to the `<body>` element. ```rust app .insert_resource(WindowDescriptor { fit_canvas_to_parent: true, ..default() }) ``` And CSS: ```css html, body { margin: 0; height: 100%; } ``` ## Fit custom canvas to "wrapper" parent element ```rust app .insert_resource(WindowDescriptor { fit_canvas_to_parent: true, canvas: Some("#bevy".to_string()), ..default() }) ``` And the HTML: ```html <div style="width: 50%; height: 100%"> <canvas id="bevy"></canvas> </div> ```
- Loading branch information
Showing
4 changed files
with
154 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
use crate::WinitWindows; | ||
use bevy_app::{App, Plugin}; | ||
use bevy_ecs::prelude::*; | ||
use bevy_window::WindowId; | ||
use crossbeam_channel::{Receiver, Sender}; | ||
use wasm_bindgen::JsCast; | ||
use winit::dpi::LogicalSize; | ||
|
||
pub(crate) struct CanvasParentResizePlugin; | ||
|
||
impl Plugin for CanvasParentResizePlugin { | ||
fn build(&self, app: &mut App) { | ||
app.init_resource::<CanvasParentResizeEventChannel>() | ||
.add_system(canvas_parent_resize_event_handler); | ||
} | ||
} | ||
|
||
struct ResizeEvent { | ||
size: LogicalSize<f32>, | ||
window_id: WindowId, | ||
} | ||
|
||
pub(crate) struct CanvasParentResizeEventChannel { | ||
sender: Sender<ResizeEvent>, | ||
receiver: Receiver<ResizeEvent>, | ||
} | ||
|
||
fn canvas_parent_resize_event_handler( | ||
winit_windows: Res<WinitWindows>, | ||
resize_events: Res<CanvasParentResizeEventChannel>, | ||
) { | ||
for event in resize_events.receiver.try_iter() { | ||
if let Some(window) = winit_windows.get_window(event.window_id) { | ||
window.set_inner_size(event.size); | ||
} | ||
} | ||
} | ||
|
||
fn get_size(selector: &str) -> Option<LogicalSize<f32>> { | ||
let win = web_sys::window().unwrap(); | ||
let doc = win.document().unwrap(); | ||
let element = doc.query_selector(selector).ok()??; | ||
let parent_element = element.parent_element()?; | ||
let rect = parent_element.get_bounding_client_rect(); | ||
return Some(winit::dpi::LogicalSize::new( | ||
rect.width() as f32, | ||
rect.height() as f32, | ||
)); | ||
} | ||
|
||
pub(crate) const WINIT_CANVAS_SELECTOR: &str = "canvas[data-raw-handle]"; | ||
|
||
impl Default for CanvasParentResizeEventChannel { | ||
fn default() -> Self { | ||
let (sender, receiver) = crossbeam_channel::unbounded(); | ||
return Self { sender, receiver }; | ||
} | ||
} | ||
|
||
impl CanvasParentResizeEventChannel { | ||
pub(crate) fn listen_to_selector(&self, window_id: WindowId, selector: &str) { | ||
let sender = self.sender.clone(); | ||
let owned_selector = selector.to_string(); | ||
let resize = move || { | ||
if let Some(size) = get_size(&owned_selector) { | ||
sender.send(ResizeEvent { size, window_id }).unwrap(); | ||
} | ||
}; | ||
|
||
// ensure resize happens on startup | ||
resize(); | ||
|
||
let closure = wasm_bindgen::closure::Closure::wrap(Box::new(move |_: web_sys::Event| { | ||
resize(); | ||
}) as Box<dyn FnMut(_)>); | ||
let window = web_sys::window().unwrap(); | ||
|
||
window | ||
.add_event_listener_with_callback("resize", closure.as_ref().unchecked_ref()) | ||
.unwrap(); | ||
closure.forget(); | ||
} | ||
} |