search
HomeWeb Front-endCSS TutorialAn Interactive Starry Backdrop for Content

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);

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!

Statement
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
A Little Reminder That Pseudo Elements are Children, Kinda.A Little Reminder That Pseudo Elements are Children, Kinda.Apr 19, 2025 am 11:39 AM

Here's a container with some child elements:

Menus with 'Dynamic Hit Areas'Menus with 'Dynamic Hit Areas'Apr 19, 2025 am 11:37 AM

Flyout menus! The second you need to implement a menu that uses a hover event to display more menu items, you're in tricky territory. For one, they should

Improving Video Accessibility with WebVTTImproving Video Accessibility with WebVTTApr 19, 2025 am 11:27 AM

"The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect."- Tim Berners-Lee

Weekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteWeekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteApr 19, 2025 am 11:25 AM

In this week's roundup: datepickers are giving keyboard users headaches, a new web component compiler that helps fight FOUC, we finally get our hands on styling list item markers, and four steps to getting webmentions on your site.

Making width and flexible items play nice togetherMaking width and flexible items play nice togetherApr 19, 2025 am 11:23 AM

The short answer: flex-shrink and flex-basis are probably what you’re lookin’ for.

Position Sticky and Table HeadersPosition Sticky and Table HeadersApr 19, 2025 am 11:21 AM

You can't position: sticky; a

Weekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryWeekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryApr 19, 2025 am 11:18 AM

In this week's look around the world of web platform news, Google Search Console makes it easier to view crawled markup, we learn that custom properties

IndieWeb and WebmentionsIndieWeb and WebmentionsApr 19, 2025 am 11:16 AM

The IndieWeb is a thing! They've got a conference coming up and everything. The New Yorker is even writing about it:

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor