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.
Building the Basic App
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; }
Adding Stars
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).
Adding Interactivity
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); };
Bonus: Konami Code Easter Egg
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
