国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Building the Basic App
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>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 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

CSS: When Does Case Matter (and When Doesn't)? CSS: When Does Case Matter (and When Doesn't)? Jun 19, 2025 am 12:27 AM

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

See all articles