As an experiment, I replaced the banner of one of the pages on my website with an HTML canvas element that features a simple, interactive asteroid simulation. This dynamic banner adds a lively touch, with a starship that follows the mouse and evades asteroids, creating an engaging, immersive experience.
To ensure the title is visible, I set the position to be relative and used a z-index
of 2
so it sits on top of the canvas:
<header class="masthead">
<div class="container position-relative px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<div class="site-heading">
<h1 style="position: relative; z-index: 2;">HTML5 APP</h1>
<span class="subheading"></span>
</div>
</div>
</div>
</div>
<canvas id="asteroid-canvas"></canvas>
</header>
To set up the canvas as a full-width banner, I used CSS to position the canvas in the same location as the previous banner image. The background is set to black to provide a space-like atmosphere:
#asteroid-canvas {
position: absolute;
top: 0;
left: 0;
background-color: #2C2C2C;
}
This CSS positions the canvas element to fully cover the banner area, making it responsive and adapting to different screen sizes.
For the animation, I used JavaScript to create and animate the asteroids and the starship. The code initializes a different number of asteroids based on screen size: 10 for desktop and 5 for mobile devices. This is achieved by detecting the screen width using window.innerWidth
, and then calling createAsteroids
with the appropriate count. Here’s the snippet:
if (window.innerWidth > 768) { // Desktop
createAsteroids(10);
} else { // Mobile
createAsteroids(5);
}
The JavaScript also includes functionality for mouse tracking, so the starship follows the mouse pointer. It detects collisions between the starship and the asteroids, temporarily halting the starship if a collision is detected and resuming its path when clear.