Example p5js Loading Screen
by Paul Wheeler
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
<style>
#loading_screen {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
body.loaded #loading_screen {
display: none;
}
</style>
<!-- if you include other heafty javascript files here, use the defer attribute -->
</head>
<body>
<div id="root">
<!-- this is where your SPA content will show up -->
NOTHING TO SEE HERE YET
</div>
<div id="loading_screen">
<!-- this is where the p5js loading screen canvas will be -->
</div>
<script>
function LoadingScreen(p) {
p.setup = function() {
p.createCanvas(p.windowWidth, p.windowHeight);
}
p.draw = function() {
p.background(200, 200, 200, 20);
p.circle(
p.width / 2 + p.cos(p.millis() / 400) * 100,
p.height / 2 + p.sin(p.millis() / 400) * 100,
100
);
}
}
let sketch = new p5(LoadingScreen, 'loading_screen');
document.addEventListener('appLoaded', () => {
// Make the loading screen go away
sketch.remove(); // This removes the canvas
document.body.classList.add('loaded'); // This stops displaying the div
});
</script>
<script>
<!-- Imagine this is some script that runs once your app is done bootstrapping
-->
<!-- Where exactly this code goes depends on your SPA framework -->
setTimeout(
() => {
let root = document.getElementById('root');
root.innerHTML = 'Hooray our app has loaded!';
document.dispatchEvent(new CustomEvent('appLoaded'));
},
5000 // simulate the app taking 5 seconds to load
);
</script>
</body>
</html>