diff --git a/Cargo.toml b/Cargo.toml index 8b205568e13e4..0c997a8f9e66c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -274,4 +274,4 @@ required-features = [] [[example]] name = "winit_wasm" path = "examples/wasm/winit_wasm.rs" -required-features = [] +required-features = ["bevy_winit"] diff --git a/crates/bevy_winit/Cargo.toml b/crates/bevy_winit/Cargo.toml index 8d7b7a64733ea..30f97a85bb532 100644 --- a/crates/bevy_winit/Cargo.toml +++ b/crates/bevy_winit/Cargo.toml @@ -31,3 +31,4 @@ log = { version = "0.4", features = ["release_max_level_info"] } [target.'cfg(target_arch = "wasm32")'.dependencies] winit = { version = "0.22.2", package = "cart-tmp-winit", features = ["web-sys"] } +web-sys = "0.3" diff --git a/crates/bevy_winit/src/winit_windows.rs b/crates/bevy_winit/src/winit_windows.rs index 3eb1aac00a229..9ec2c88e15fa2 100644 --- a/crates/bevy_winit/src/winit_windows.rs +++ b/crates/bevy_winit/src/winit_windows.rs @@ -46,6 +46,20 @@ impl WinitWindows { self.window_id_to_winit.insert(window.id, winit_window.id()); self.winit_to_window_id.insert(winit_window.id(), window.id); + #[cfg(target_arch = "wasm32")] + { + use winit::platform::web::WindowExtWebSys; + + let canvas = winit_window.canvas(); + + let window = web_sys::window().unwrap(); + let document = window.document().unwrap(); + let body = document.body().unwrap(); + + body.append_child(&canvas) + .expect("Append canvas to HTML body"); + } + self.windows.insert(winit_window.id(), winit_window); } diff --git a/examples/README.md b/examples/README.md index 117e11d3b3f58..48ede21f9d878 100644 --- a/examples/README.md +++ b/examples/README.md @@ -126,6 +126,10 @@ Example | File | Description #### build & run +Following is an example for `headless_wasm`. For other examples in wasm/ directory, +change the `headless_wasm` in the following commands **and edit** `examples/wasm/index.html` +to point to the correct `.js` file. + $ cargo build --example headless_wasm --target wasm32-unknown-unknown --no-default-features $ wasm-bindgen --out-dir examples/wasm/target --target web target/wasm32-unknown-unknown/debug/examples/headless_wasm.wasm diff --git a/examples/wasm/index.html b/examples/wasm/index.html index 929142536e8ad..33f18ca24fdf7 100644 --- a/examples/wasm/index.html +++ b/examples/wasm/index.html @@ -1,6 +1,24 @@
+