Home >Web Front-end >CSS Tutorial >An Interactive Starry Backdrop for Content
Last year, I had the opportunity to collaborate with Shawn Wang (swyx) on a project for Temporal. The goal was to enhance their website with some creative elements. This was a fascinating challenge, as I'm more of a developer than a designer, but I embraced the chance to expand my design skills.
One of my contributions was an interactive starry backdrop. You can see it in action here:
Blockquote concept using perspective and CSS custom properties. Enjoying the creative freedom at @temporalio. Adding a touch of whimsy! ⚒️ @reactjs && @tailwindcss (Site is NextJS) ? Link to CodePen via @CodePen pic.twitter.com/s9xP2tRrOx
— Jhey ??✨ (@jh3yy) July 2, 2021
This design's strength lies in its implementation as a reusable React component, offering high configurability. Need different shapes instead of stars? Want to control particle placement precisely? You're in complete control.
Let's build this component! We'll use React, GreenSock, and the HTML <canvas></canvas>
element. React is optional, but using it creates a reusable component for future projects.
import React from 'https://cdn.skypack.dev/react'; import ReactDOM from 'https://cdn.skypack.dev/react-dom'; import gsap from 'https://cdn.skypack.dev/gsap'; const ROOT_NODE = document.querySelector('#app'); const Starscape = () => <h1>Cool Thingzzz!</h1>; const App = () => <starscape></starscape>; ReactDOM.render(<app></app>, ROOT_NODE);
First, we render a <canvas></canvas>
element and grab a reference for use within React's useEffect
hook. If not using React, store the reference directly in a variable.
const Starscape = () => { const canvasRef = React.useRef(null); return <canvas ref="{canvasRef}"></canvas>; };
We'll style the <canvas></canvas>
to fill the viewport and sit behind the content:
canvas { position: fixed; inset: 0; background: #262626; z-index: -1; height: 100vh; width: 100vw; }
We'll simplify star rendering by using circles with varying opacities and sizes. Drawing a circle on a <canvas></canvas>
involves getting the context and using the arc
function. Let's render a circle (our star) in the center using a useEffect
hook:
const Starscape = () => { const canvasRef = React.useRef(null); const contextRef = React.useRef(null); React.useEffect(() => { canvasRef.current.width = window.innerWidth; canvasRef.current.height = window.innerHeight; contextRef.current = canvasRef.current.getContext('2d'); contextRef.current.fillStyle = 'yellow'; contextRef.current.beginPath(); contextRef.current.arc( window.innerWidth / 2, // X window.innerHeight / 2, // Y 100, // Radius 0, // Start Angle (Radians) Math.PI * 2 // End Angle (Radians) ); contextRef.current.fill(); }, []); return <canvas ref="{canvasRef}"></canvas>; };
This creates a yellow circle. The remaining code will be within this useEffect
. This is why the React part is optional; you can adapt this code for other frameworks.
We need to generate and render multiple stars. Let's create a LOAD
function to handle star generation and canvas setup, including canvas sizing:
const LOAD = () => { const VMIN = Math.min(window.innerHeight, window.innerWidth); const STAR_COUNT = Math.floor(VMIN * densityRatio); canvasRef.current.width = window.innerWidth; canvasRef.current.height = window.innerHeight; starsRef.current = new Array(STAR_COUNT).fill().map(() => ({ x: gsap.utils.random(0, window.innerWidth, 1), y: gsap.utils.random(0, window.innerHeight, 1), size: gsap.utils.random(1, sizeLimit, 1), scale: 1, alpha: gsap.utils.random(0.1, defaultAlpha, 0.1), })); };
Each star is an object with properties defining its characteristics (x, y position, size, scale, alpha). sizeLimit
, defaultAlpha
, and densityRatio
are props passed to the Starscape
component with default values.
A sample star object:
{ "x": 1252, "y": 29, "size": 4, "scale": 1, "alpha": 0.5 }
To render these stars, we create a RENDER
function that iterates over the stars
array and renders each star using the arc
function:
const RENDER = () => { contextRef.current.clearRect( 0, 0, canvasRef.current.width, canvasRef.current.height ); starsRef.current.forEach((star) => { contextRef.current.fillStyle = `hsla(0, 100%, 100%, ${star.alpha})`; contextRef.current.beginPath(); contextRef.current.arc(star.x, star.y, star.size / 2, 0, Math.PI * 2); contextRef.current.fill(); }); };
The clearRect
function clears the canvas before rendering, which is crucial for animation.
The complete Starscape
component (without interactivity yet) is shown below:
Complete Starscape Component (without interactivity)
const Starscape = ({ densityRatio = 0.5, sizeLimit = 5, defaultAlpha = 0.5 }) => { const canvasRef = React.useRef(null); const contextRef = React.useRef(null); const starsRef = React.useRef(null); React.useEffect(() => { contextRef.current = canvasRef.current.getContext('2d'); const LOAD = () => { const VMIN = Math.min(window.innerHeight, window.innerWidth); const STAR_COUNT = Math.floor(VMIN * densityRatio); canvasRef.current.width = window.innerWidth; canvasRef.current.height = window.innerHeight; starsRef.current = new Array(STAR_COUNT).fill().map(() => ({ x: gsap.utils.random(0, window.innerWidth, 1), y: gsap.utils.random(0, window.innerHeight, 1), size: gsap.utils.random(1, sizeLimit, 1), scale: 1, alpha: gsap.utils.random(0.1, defaultAlpha, 0.1), })); }; const RENDER = () => { contextRef.current.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height); starsRef.current.forEach((star) => { contextRef.current.fillStyle = `hsla(0, 100%, 100%, ${star.alpha})`; contextRef.current.beginPath(); contextRef.current.arc(star.x, star.y, star.size / 2, 0, Math.PI * 2); contextRef.current.fill(); }); }; const RUN = () => { LOAD(); RENDER(); }; RUN(); window.addEventListener('resize', RUN); return () => { window.removeEventListener('resize', RUN); }; }, []); return <canvas ref="{canvasRef}"></canvas>; };
Experiment with the props in a demo to see their effects. To handle viewport resizing, we call LOAD
and RENDER
on resize (with debouncing for optimization, which is omitted for brevity here).
Now, let's make the backdrop interactive. When the pointer moves, stars near the cursor brighten and scale up.
We'll add an UPDATE
function to calculate the distance between the pointer and each star, then tween the star's scale and alpha using GreenSock's mapRange
utility. We'll also add scaleLimit
and proximityRatio
props to control the scaling behavior.
const UPDATE = ({ x, y }) => { starsRef.current.forEach((star) => { const DISTANCE = Math.sqrt(Math.pow(star.x - x, 2) Math.pow(star.y - y, 2)); gsap.to(star, { scale: scaleMapperRef.current(Math.min(DISTANCE, vminRef.current * proximityRatio)), alpha: alphaMapperRef.current(Math.min(DISTANCE, vminRef.current * proximityRatio)), }); }); };
To render updates, we use gsap.ticker
(a good alternative to requestAnimationFrame
), adding RENDER
to the ticker and removing it in the cleanup. We set the frames per second (fps) to 24. The RENDER
function now uses the star.scale
value when drawing the arc.
LOAD(); gsap.ticker.add(RENDER); gsap.ticker.fps(24); window.addEventListener('resize', LOAD); document.addEventListener('pointermove', UPDATE); return () => { window.removeEventListener('resize', LOAD); document.removeEventListener('pointermove', UPDATE); gsap.ticker.remove(RENDER); };
Now, when you move your mouse, the stars react!
To handle the case where the mouse leaves the canvas, we add a pointerleave
event listener that tweens the stars back to their original state:
const EXIT = () => { gsap.to(starsRef.current, { scale: 1, alpha: defaultAlpha }); }; // ... event listeners ... document.addEventListener('pointerleave', EXIT); return () => { // ... cleanup ... document.removeEventListener('pointerleave', EXIT); gsap.ticker.remove(RENDER); };
Let's add a Konami Code Easter egg. We'll listen for keyboard events and trigger an animation if the code is entered.
const KONAMI_CODE = 'ArrowUp,ArrowUp,ArrowDown,ArrowDown,ArrowLeft,ArrowRight,ArrowLeft,ArrowRight,KeyB,KeyA'; const codeRef = React.useRef([]); React.useEffect(() => { const handleCode = (e) => { codeRef.current = [...codeRef.current, e.code].slice(codeRef.current.length > 9 ? codeRef.current.length - 9 : 0); if (codeRef.current.join(',').toLowerCase() === KONAMI_CODE.toLowerCase()) { // Trigger Easter egg animation } }; window.addEventListener('keyup', handleCode); return () => { window.removeEventListener('keyup', handleCode); }; }, []);
The complete, interactive Starscape
component with the Konami Code Easter egg is quite lengthy and omitted here for brevity. However, the principles outlined above demonstrate how to create a fully functional and customizable interactive starry backdrop using React, GreenSock, and HTML <canvas></canvas>
. The Easter egg animation would involve creating a gsap.timeline
to animate star properties.
This example demonstrates the techniques needed to create your own custom backdrops. Remember to consider how the backdrop interacts with your site's content. Experiment with different shapes, colors, and animations to create unique and engaging visuals.
The above is the detailed content of An Interactive Starry Backdrop for Content. For more information, please follow other related articles on the PHP Chinese website!