# Space Hero Background

Space Hero Background is a backdrop for a hero section: neon streaks fly out of the center like stars in a jump to hyperspace, while a soft glow shifts along the edges.

- Live demo: https://dmivanov.ru/experiments/space-hero
- Original CodePen: https://codepen.io/divulture/pen/azNVEQg

## How to embed

Instructions for an AI agent or developer adding this effect to a website.

1. Save the two code blocks below as `shared.js` and `space-hero.js` in the same folder of the project's scripts. They are plain ES modules with no build step and no dependencies.
2. Add a container with an explicit size where the effect should appear. The effect fills it completely:

   ```html
   <div id="space-hero" style="position: relative; width: 100%; height: 480px;"></div>
   ```

3. Mount the effect from a module script:

   ```html
   <script type="module">
     import { mount, meta } from "./space-hero.js";

     const effect = mount(document.getElementById("space-hero"), { ...meta.defaults });
     // effect.update({ ... }) changes parameters at runtime.
     // effect.replay() restarts one-shot animations.
     // effect.destroy() removes the effect and its listeners.
   </script>
   ```

The module injects its own CSS and loads its Google Font. Pixel values are authored for a 1000px-wide container and scale with the container width. In React, Vue or Svelte, call `mount` when the component mounts and `destroy` when it unmounts. Pass `{ mode: "still" }` as the third argument of `mount` to render a single static frame, for example for a preview card.

## Parameters

| Key | Control | Default | Values |
| --- | --- | --- | --- |
| `title` | Title | `"AI infrastructure that developers love"` | text, up to 60 chars |
| `count` | Streaks | `86` | 20–200 |
| `speed` | Speed | `1` | 0.2–3 x |
| `length` | Length | `1` | 0.3–2.5 x |
| `parallax` | Parallax | `6` | 0–20 % |
| `background` | Background | `"#171717"` | hex color |

## shared.js

```js
// Shared helpers for experiment modules.
//
// Every experiment exports `meta` (title, controls, defaults) and
// `mount(stage, settings, { mode })`. The stage is any positioned element; the
// effect fills it and scales its pixel values to the stage width, so the same
// code runs in the full demo, in small card previews, and on a client's site.
// `mode` is "live" (interactive / animated) or "still" (one static frame).

export const REFERENCE_WIDTH = 1000;

const fontRequests = new Map();

// Loads a Google Fonts stylesheet once and resolves when the family is ready.
export function loadFont(href, family, weight = "400") {
  if (!href || typeof document === "undefined") return Promise.resolve();
  const key = `${family}:${weight}`;
  if (fontRequests.has(key)) return fontRequests.get(key);
  // The @font-face rules exist only after the stylesheet loads, so wait for
  // it before asking the browser to fetch the font itself.
  let link = document.querySelector(`link[href="${href}"]`);
  const stylesheet = link && link.sheet ? Promise.resolve() : new Promise((resolve) => {
    if (!link) {
      link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = href;
      document.head.append(link);
    }
    link.addEventListener("load", resolve, { once: true });
    link.addEventListener("error", resolve, { once: true });
  });
  const request = stylesheet
    .then(() => (document.fonts ? document.fonts.load(`${weight} 32px "${family}"`) : null))
    .catch(() => {})
    .then(() => undefined);
  fontRequests.set(key, request);
  return request;
}

export function loadFonts(fonts = []) {
  return Promise.all(fonts.map((font) => loadFont(font.href, font.family, font.weight)));
}

// Adds a stylesheet for an effect once per document.
export function injectStyle(id, css) {
  if (typeof document === "undefined" || document.getElementById(id)) return;
  const style = document.createElement("style");
  style.id = id;
  style.textContent = css;
  document.head.append(style);
}

// Pixel values in settings are authored for a 1000px-wide stage.
export function stageUnit(stage) {
  return (stage.clientWidth || REFERENCE_WIDTH) / REFERENCE_WIDTH;
}

// Every effect keeps the same margin inside its stage: 8% of the stage width.
export const SAFE_AREA = 0.08;

export function safeArea(stage) {
  const pad = Math.round(stage.clientWidth * SAFE_AREA);
  return {
    pad,
    width: Math.max(1, stage.clientWidth - pad * 2),
    height: Math.max(1, stage.clientHeight - pad * 2)
  };
}

// Scale that fits a box of the given size into the safe area. Previews pass
// `grow` so every card fills its safe area the same way; the full demo only
// shrinks content that would otherwise overflow. `fill` lets a preview whose
// type reads heavy take less of the area than the others.
export function fitScale(stage, width, height, { grow = false, fill = 1 } = {}) {
  if (!width || !height) return 1;
  const area = safeArea(stage);
  const scale = Math.min(area.width / width, area.height / height);
  return grow ? scale * fill : Math.min(1, scale);
}

// Fits an element by its layout size (transforms do not affect offset sizes)
// and writes the result to its `--fx-fit` custom property.
export function fitElement(stage, element, options) {
  const scale = fitScale(stage, element.offsetWidth, element.offsetHeight, options);
  element.style.setProperty("--fx-fit", scale.toFixed(4));
  return scale;
}

export function watchSize(stage, callback) {
  if (typeof ResizeObserver === "undefined") return () => {};
  let width = stage.clientWidth;
  let height = stage.clientHeight;
  const observer = new ResizeObserver(() => {
    if (stage.clientWidth === width && stage.clientHeight === height) return;
    width = stage.clientWidth;
    height = stage.clientHeight;
    callback();
  });
  observer.observe(stage);
  return () => observer.disconnect();
}

export function localPoint(stage, event) {
  const rect = stage.getBoundingClientRect();
  return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}

let uid = 0;
export function uniqueId(prefix) {
  uid += 1;
  return `${prefix}-${uid}`;
}

// Splits text into words and letters without touching the original string.
export function splitWords(text) {
  return String(text).trim().split(/\s+/).filter(Boolean);
}

export function isHexColor(value) {
  return /^#[0-9a-f]{6}$/i.test(String(value));
}
```

## space-hero.js

```js
import { injectStyle, loadFonts, localPoint, stageUnit, watchSize } from "./shared.js";

export const meta = {
  slug: "space-hero",
  description: "Space Hero Background is a backdrop for a hero section: neon streaks fly out of the center like stars in a jump to hyperspace, while a soft glow shifts along the edges.",
  title: "Space Hero Background",
  codepen: "https://codepen.io/divulture/pen/azNVEQg",
  replay: false,
  fonts: [{ family: "Manrope", weight: "300", href: "https://fonts.googleapis.com/css2?family=Manrope:wght@300&display=swap" }],
  controls: [
    { key: "title", label: "Title", type: "text", maxlength: 60 },
    { key: "count", label: "Streaks", type: "range", min: 20, max: 200, step: 2, unit: "" },
    { key: "speed", label: "Speed", type: "range", min: 0.2, max: 3, step: 0.1, unit: "x" },
    { key: "length", label: "Length", type: "range", min: 0.3, max: 2.5, step: 0.1, unit: "x" },
    { key: "parallax", label: "Parallax", type: "range", min: 0, max: 20, step: 1, unit: "%" },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    title: "AI infrastructure that developers love",
    count: 86,
    speed: 1,
    length: 1,
    parallax: 6,
    background: "#171717"
  }
};

const COLORS = [
  { r: 98, g: 255, b: 210 },
  { r: 87, g: 246, b: 197 },
  { r: 92, g: 238, b: 180 },
  { r: 76, g: 215, b: 255 },
  { r: 104, g: 234, b: 255 },
  { r: 64, g: 196, b: 220 }
];

const CSS = `
.fx-space { position: absolute; inset: 0; overflow: hidden; background: var(--fx-bg); }
.fx-space canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.fx-space__glow { z-index: 3; pointer-events: none; }
.fx-space__mask { position: absolute; top: 50%; left: 50%; z-index: 1; width: 32%; aspect-ratio: 1; border-radius: 50%; background: var(--fx-bg); box-shadow: 0 0 32px var(--fx-bg), 0 0 88px var(--fx-bg); filter: blur(12px); transform: translate(-50%, -50%); pointer-events: none; }
.fx-space__title { position: absolute; inset: 0; z-index: 2; display: grid; place-items: center; margin: 0; padding: 0 8%; font-family: "Manrope", sans-serif; font-weight: 300; line-height: 1; letter-spacing: -.02em; text-align: center; pointer-events: none; }
.fx-space__title span { background: linear-gradient(180deg, #e6edf2 70%, rgba(128, 106, 106, 0) 100%); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; }
`;

const isChrome = typeof navigator !== "undefined" && /Chrome/i.test(navigator.userAgent) && !/Edg|OPR/i.test(navigator.userAgent);

export function mount(stage, initialSettings, { mode = "live", preview = false } = {}) {
  injectStyle("fx-space-style", CSS);
  let settings = { ...meta.defaults, ...initialSettings };
  const root = document.createElement("div");
  root.className = "fx-space";
  const warp = document.createElement("canvas");
  const mask = document.createElement("div");
  mask.className = "fx-space__mask";
  const title = document.createElement("p");
  title.className = "fx-space__title";
  const titleText = document.createElement("span");
  title.append(titleText);
  const glow = document.createElement("canvas");
  glow.className = "fx-space__glow";
  root.append(warp, mask, title, glow);
  stage.append(root);
  const ctx = warp.getContext("2d");
  const gctx = glow.getContext("2d");
  const dpr = Math.min(window.devicePixelRatio || 1, isChrome ? 1 : 1.25);

  let width = 0;
  let height = 0;
  let unit = 1;
  let streaks = [];
  const glows = [];
  const pointer = { x: null, y: null };
  let frame = 0;
  let last = performance.now();
  let glowTimer = 0;

  function makeStreak(initial) {
    const speed = 260 + Math.random() * 720;
    const depth = 0.35 + Math.random() * 1.4;
    const speedNorm = Math.min(1, Math.max(0, (speed - 260) / 720));
    const fadeStart = Math.min(0.9, 0.38 + Math.random() * 0.08 + speedNorm * 0.22);
    return {
      angle: Math.random() * Math.PI * 2,
      speed,
      length: 80 + Math.random() * 280,
      depth,
      alpha: 0.35 + Math.random() * 0.55,
      distance: initial ? Math.random() * Math.max(width, height) * 0.25 : 0,
      color: COLORS[Math.floor(Math.random() * COLORS.length)],
      thickness: (0.9 + Math.pow(Math.random(), 0.45) * 2.4) / depth,
      flickerPhase: Math.random() * Math.PI * 2,
      speedJitter: 0.7 + Math.random() * 0.3,
      tailFactor: 0.55 + Math.random() * 0.12,
      fadeStart,
      fadeEnd: Math.min(0.98, fadeStart + 0.22 + Math.random() * 0.08 + speedNorm * 0.18),
      blur: 0.2 + Math.random() * 0.6,
      noFade: Math.random() < 0.35,
      dualFade: Math.random() < 0.45
    };
  }

  function resize() {
    unit = stageUnit(stage);
    width = root.clientWidth;
    height = root.clientHeight;
    [warp, glow].forEach((canvas) => {
      canvas.width = width * dpr;
      canvas.height = height * dpr;
    });
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    gctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    glows.length = 0;
    title.style.fontSize = `${112 * unit}px`;
  }

  function syncCount() {
    while (streaks.length < settings.count) streaks.push(makeStreak(true));
    streaks.length = Math.round(settings.count);
  }

  function spawnGlow() {
    const side = Math.floor(Math.random() * 4);
    const x = side === 1 ? width : side === 3 ? 0 : Math.random() * width;
    const y = side === 0 ? 0 : side === 2 ? height : Math.random() * height;
    const rise = 0.4 + Math.random() * 0.35;
    glows.push({
      x, y,
      radius: Math.max(800 * unit, Math.min(width, height) * (0.24 + Math.random() * 0.16)),
      color: COLORS[Math.floor(Math.random() * COLORS.length)],
      age: 0,
      lifetime: 2.6 + Math.random() * 2.4,
      alpha: 0.14 + Math.random() * 0.14,
      driftX: (Math.random() - 0.5) * rise,
      driftY: (Math.random() - 0.5) * rise,
      blur: (256 + Math.random() * 48) * (isChrome ? 0.65 : 1) * unit
    });
  }

  function drawGlows(dt) {
    for (let i = glows.length - 1; i >= 0; i--) {
      const g = glows[i];
      g.age += dt;
      g.x += g.driftX;
      g.y += g.driftY;
      if (g.age > g.lifetime) glows.splice(i, 1);
    }
    if (glows.length < (isChrome ? 2 : 3) && Math.random() < (isChrome ? 0.16 : 0.25)) spawnGlow();
    gctx.clearRect(0, 0, width, height);
    gctx.save();
    gctx.globalCompositeOperation = "screen";
    for (const g of glows) {
      const t = g.age / g.lifetime;
      const alpha = Math.max(0, g.alpha * (t < 0.2 ? t / 0.2 : t > 0.8 ? (1 - t) / 0.2 : 1));
      const { r, g: gr, b } = g.color;
      const gradient = gctx.createRadialGradient(g.x, g.y, g.radius * 0.12, g.x, g.y, g.radius);
      gradient.addColorStop(0, `rgba(${r}, ${gr}, ${b}, ${alpha})`);
      gradient.addColorStop(0.7, `rgba(${r}, ${gr}, ${b}, ${alpha * 0.45})`);
      gradient.addColorStop(1, "rgba(0,0,0,0)");
      gctx.filter = `blur(${g.blur}px)`;
      gctx.fillStyle = gradient;
      gctx.beginPath();
      gctx.arc(g.x, g.y, g.radius, 0, Math.PI * 2);
      gctx.fill();
    }
    gctx.restore();
  }

  function drawStreaks(dt, now) {
    ctx.globalCompositeOperation = "source-over";
    ctx.fillStyle = settings.background;
    ctx.fillRect(0, 0, width, height);
    const centerX = width / 2;
    const centerY = height / 2;
    const strength = settings.parallax / 100;
    const originX = centerX + ((pointer.x ?? centerX) - centerX) * strength;
    const originY = centerY + ((pointer.y ?? centerY) - centerY) * strength;
    const maxTravel = Math.max(width, height) * 0.8;
    ctx.globalCompositeOperation = "lighter";
    ctx.lineCap = "round";
    for (let i = 0; i < streaks.length; i++) {
      let s = streaks[i];
      s.distance += s.speed * unit * settings.speed * dt * (1 / s.depth) * s.speedJitter;
      const length = s.length * unit * settings.length;
      if (s.distance - length > maxTravel) {
        s = streaks[i] = makeStreak(false);
      }
      const perspective = 0.45 + (1 / s.depth) * 0.55;
      const head = s.distance * perspective;
      const tail = Math.max(0, head - length * perspective * s.tailFactor);
      const nx = Math.cos(s.angle);
      const ny = Math.sin(s.angle);
      const x1 = originX + nx * tail;
      const y1 = originY + ny * tail;
      const x2 = originX + nx * head;
      const y2 = originY + ny * head;
      const flicker = 0.9 + Math.sin(now * 0.004 + s.flickerPhase) * 0.1;
      const r = Math.min(255, s.color.r * flicker);
      const g = Math.min(255, s.color.g * flicker);
      const b = Math.min(255, s.color.b * flicker);
      const travel = Math.min(1, s.distance / maxTravel);
      const k = Math.min(1, Math.max(0, (travel - s.fadeStart) / Math.max(0.001, s.fadeEnd - s.fadeStart)));
      const alpha = s.alpha * 0.9 * perspective * (s.noFade ? 1 : 1 - k * k * (3 - 2 * k));
      const gradient = ctx.createLinearGradient(x1, y1, x2, y2);
      gradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, 0)`);
      if (s.dualFade) {
        gradient.addColorStop(0.25, `rgba(${r}, ${g}, ${b}, ${alpha * 0.75})`);
        gradient.addColorStop(0.7, `rgba(${r}, ${g}, ${b}, ${alpha})`);
        gradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
      } else {
        gradient.addColorStop(0.65, `rgba(${r}, ${g}, ${b}, ${alpha * 0.5})`);
        gradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, ${alpha})`);
      }
      ctx.lineWidth = Math.max(0.6, s.thickness * perspective * (0.7 + travel * 0.9) * unit);
      ctx.strokeStyle = gradient;
      ctx.shadowColor = `rgba(${r}, ${g}, ${b}, ${alpha * 0.8})`;
      ctx.shadowBlur = (4 + s.blur * 6) * perspective * (isChrome ? 0.68 : 1) * unit;
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.stroke();
    }
  }

  function loop(now) {
    const dt = Math.min((now - last) / 1000, 0.033);
    last = now;
    glowTimer += dt;
    if (glowTimer >= (isChrome ? 0.12 : 0.08)) {
      drawGlows(glowTimer);
      glowTimer = 0;
    }
    drawStreaks(dt, now);
    frame = requestAnimationFrame(loop);
  }

  function render() {
    root.style.setProperty("--fx-bg", settings.background);
    titleText.textContent = settings.title;
    syncCount();
  }

  function onMove(event) {
    const point = localPoint(stage, event);
    pointer.x = point.x;
    pointer.y = point.y;
  }

  resize();
  render();
  loadFonts(meta.fonts);
  const stopWatching = watchSize(stage, resize);
  if (mode === "live") {
    stage.addEventListener("pointermove", onMove);
    frame = requestAnimationFrame(loop);
  } else {
    // A still frame: advance the streaks a little so they are spread out.
    for (let i = 0; i < 2; i++) spawnGlow();
    drawGlows(0.8);
    drawStreaks(0.4, 0);
  }

  return {
    update(next) {
      settings = { ...settings, ...next };
      render();
    },
    replay() {},
    destroy() {
      cancelAnimationFrame(frame);
      stage.removeEventListener("pointermove", onMove);
      stopWatching();
      root.remove();
    }
  };
}
```
