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:
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:
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:
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.