From e579372a46287c35601bbd144b695c51acf03041 Mon Sep 17 00:00:00 2001 From: Tim Jentzsch Date: Thu, 8 Dec 2022 15:59:18 +0100 Subject: [PATCH] Add a loading screen to the web page --- wasm/.gitignore | 3 +++ wasm/index.html | 50 +++++++++++++++++++++++++++++++++++ wasm/loading_screen.mjs | 58 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+) create mode 100644 wasm/.gitignore create mode 100644 wasm/index.html create mode 100644 wasm/loading_screen.mjs diff --git a/wasm/.gitignore b/wasm/.gitignore new file mode 100644 index 0000000..e24af31 --- /dev/null +++ b/wasm/.gitignore @@ -0,0 +1,3 @@ +assets/ +bevy_game.js +bevy_game_bg.wasm diff --git a/wasm/index.html b/wasm/index.html new file mode 100644 index 0000000..9b9cead --- /dev/null +++ b/wasm/index.html @@ -0,0 +1,50 @@ + + + + + + + + + + + +
+
+ Loading... +
+
Made with Bevy
+
+ + diff --git a/wasm/loading_screen.mjs b/wasm/loading_screen.mjs new file mode 100644 index 0000000..efcea66 --- /dev/null +++ b/wasm/loading_screen.mjs @@ -0,0 +1,58 @@ +const MAX_DOT_COUNT = 3; + +window.addEventListener("DOMContentLoaded", () => { + const body = document.getElementById("body"); + const loadingScreen = document.getElementById("loading-screen"); + const dotElement = document.getElementById("loading-dots"); + + if (body === null || loadingScreen === null || dotElement === null) { + console.error("Can't find loading screen elements!"); + return; + }; + + let dotCount = 0; + + function animateLoadingDots() { + dotElement.innerText = ".".repeat(dotCount).padEnd(3, "\u{00A0}"); + + dotCount += 1; + + if (dotCount > MAX_DOT_COUNT) { + dotCount = 0; + } + } + + function removeLoadingScreen() { + clearInterval(loadingInterval); + loadingScreen.remove(); + } + + // Wait for the `canvas` element to be created + // This tells us that the game has been fully loaded + const observer = new MutationObserver((mutations) => { + for (const mutation of mutations) { + for (const addedNode of mutation.addedNodes) { + console.debug("addedNode", addedNode, addedNode.ELEMENT_NODE); + if (addedNode.ELEMENT_NODE === 1) { + /** @type HTMLElement */ + const element = addedNode; + + console.debug(element.tagName); + + if (element.tagName === "CANVAS") { + // The game has been loaded! + // We don't need the loading screen anymore + removeLoadingScreen(); + observer.disconnect(); + } + } + } + } + }); + + observer.observe(body, { + childList: true, + }); + + const loadingInterval = setInterval(animateLoadingDots, 1000); +});