Table of Contents
Building the Basic App
Cool Thingzzz!
Adding Stars
Adding Interactivity
Bonus: Konami Code Easter Egg
Home Web Front-end CSS Tutorial An Interactive Starry Backdrop for Content

An Interactive Starry Backdrop for Content

Mar 13, 2025 am 11:22 AM

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.

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 id="Cool-Thingzzz">Cool Thingzzz!</h1>;

const App = () => <starscape></starscape>;

ReactDOM.render(<app></app>, ROOT_NODE);
Copy after login

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>;
};
Copy after login

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;
}
Copy after login

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>;
};
Copy after login

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),
  }));
};
Copy after login

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
}
Copy after login

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();
  });
};
Copy after login

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>;
};
Copy after login

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)),
    });
  });
};
Copy after login

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);
};
Copy after login

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);
};
Copy after login

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);
  };
}, []);
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles