Skip to main content

Starfall Field

A canvas star field with cursor gravity: stars inside the influence radius accelerate toward the pointer while their glow eases up and their opacity lifts, clicks burst new stars into the field (capped, oldest culled), and every star drifts on a damped random walk that wraps around the edges. Rendering pauses off-screen via IntersectionObserver and the DPR is capped at 2.

HeroReactCanvas 2DTailwind CSS
CSSTailwind

Manual

Create a file and paste the following code into it.

starfall-field.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@/lib/cn";

/* ------------------------------------------------------------------ */
/*  StarfallFieldBackground                                             */
/* ------------------------------------------------------------------ */

interface Star {
  x: number;
  y: number;
  vx: number;
  vy: number;
  size: number;
  opacity: number;
  baseOpacity: number;
  mass: number;
  glow: number;
  glowVelocity: number;
}

interface StarfallFieldProps {
  /** Number of seeded stars [Optional, default: 75] */
  starsCount?: number;
  /** Max star radius in px [Optional, default: 2] */
  starsSize?: number;
  starsOpacity?: number;
  starsColor?: string;
  /** Shadow blur multiplier under the cursor [Optional, default: 15] */
  glowIntensity?: number;
  /** How the glow eases toward its target [Optional, default: "ease"] */
  glowAnimation?: "instant" | "ease" | "spring";
  movementSpeed?: number;
  /** Cursor influence radius in px [Optional, default: 100] */
  mouseInfluence?: number;
  mouseGravity?: "attract" | "repel";
  gravityStrength?: number;
  className?: string;
}

/**
 * A canvas star field with cursor gravity: stars inside the influence radius
 * accelerate toward (or away from) the pointer while their glow eases up,
 * clicks burst new stars into the field (capped, oldest culled), and every
 * star drifts on a damped random walk that wraps around the edges. Rendering
 * pauses off-screen via IntersectionObserver.
 * @param {string} starsColor - Fill + glow color [Optional, default: "#f4f4f5"]
 * @param {"attract"|"repel"} mouseGravity - Pull direction [Optional, default: "attract"]
 */
export function StarfallFieldBackground({
  starsCount = 75,
  starsSize = 2,
  starsOpacity = 0.75,
  starsColor = "#f4f4f5",
  glowIntensity = 15,
  glowAnimation = "ease",
  movementSpeed = 0.3,
  mouseInfluence = 100,
  mouseGravity = "attract",
  gravityStrength = 75,
  className,
}: StarfallFieldProps) {
  const hostRef = useRef<HTMLDivElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const rafRef = useRef<number | null>(null);
  const starsRef = useRef<Star[]>([]);
  const mouseRef = useRef({ x: -9999, y: -9999 });
  const visibleRef = useRef(true);
  const capRef = useRef(Math.max(80, starsCount));
  const [dpr, setDpr] = useState(1);
  const sizeRef = useRef({ width: 800, height: 600 });

  const makeStar = useCallback(
    (x: number, y: number, speed: number, glow = 1): Star => {
      const angle = Math.random() * Math.PI * 2;
      return {
        x,
        y,
        vx: Math.cos(angle) * speed,
        vy: Math.sin(angle) * speed,
        size: Math.random() * starsSize + 1,
        opacity: starsOpacity,
        baseOpacity: starsOpacity,
        mass: 0.5 * Math.random() + 0.5,
        glow,
        glowVelocity: 0,
      };
    },
    [starsSize, starsOpacity],
  );

  const seed = useCallback(
    (w: number, h: number) => {
      starsRef.current = Array.from({ length: starsCount }, () =>
        makeStar(Math.random() * w, Math.random() * h, movementSpeed * (0.5 + 0.5 * Math.random())),
      );
    },
    [starsCount, makeStar, movementSpeed],
  );

  /** Click: burst a few extra stars in, culling the oldest past the cap. */
  const spawn = useCallback(
    (x: number, y: number, count = 4) => {
      const burst = Array.from({ length: count }, () => makeStar(x, y, 2 + Math.random(), 2));
      const next = [...starsRef.current, ...burst];
      starsRef.current = next.length > capRef.current ? next.slice(next.length - capRef.current) : next;
    },
    [makeStar],
  );

  const fit = useCallback(() => {
    const canvas = canvasRef.current;
    const host = hostRef.current;
    if (!canvas || !host) return;
    const rect = host.getBoundingClientRect();
    const ratio = Math.max(1, Math.min(window.devicePixelRatio || 1, 2));
    setDpr(ratio);
    canvas.width = Math.max(1, Math.floor(rect.width * ratio));
    canvas.height = Math.max(1, Math.floor(rect.height * ratio));
    canvas.style.width = `${rect.width}px`;
    canvas.style.height = `${rect.height}px`;
    sizeRef.current = { width: rect.width, height: rect.height };
    if (starsRef.current.length === 0) seed(rect.width, rect.height);
  }, [seed]);

  const step = useCallback(() => {
    const { width, height } = sizeRef.current;
    const mouse = mouseRef.current;
    for (const star of starsRef.current) {
      const dx = mouse.x - star.x;
      const dy = mouse.y - star.y;
      const dist = Math.hypot(dx, dy);

      if (dist < mouseInfluence && dist > 0) {
        const force = (mouseInfluence - dist) / mouseInfluence;
        const accel = 0.001 * gravityStrength * force;
        const sign = mouseGravity === "repel" ? -1 : 1;
        star.vx += (dx / dist) * accel * sign;
        star.vy += (dy / dist) * accel * sign;
        star.opacity = Math.min(1, star.baseOpacity + 0.4 * force);
        const target = 1 + 2 * force;
        if (glowAnimation === "instant") star.glow = target;
        else if (glowAnimation === "ease") star.glow += (target - star.glow) * 0.15;
        else {
          star.glowVelocity = 0.85 * star.glowVelocity + (target - star.glow) * 0.2;
          star.glow += star.glowVelocity;
        }
      } else {
        star.opacity = Math.max(0.3 * star.baseOpacity, star.opacity - 0.02);
        if (glowAnimation === "instant") star.glow = 1;
        else if (glowAnimation === "ease") star.glow = Math.max(1, star.glow + (1 - star.glow) * 0.08);
        else {
          star.glowVelocity = 0.9 * star.glowVelocity + (1 - star.glow) * 0.15;
          star.glow = Math.max(1, star.glow + star.glowVelocity);
        }
      }

      star.x += star.vx;
      star.y += star.vy;
      star.vx += (Math.random() - 0.5) * 0.001;
      star.vy += (Math.random() - 0.5) * 0.001;
      star.vx *= 0.999;
      star.vy *= 0.999;
      if (star.x < 0) star.x = width;
      if (star.x > width) star.x = 0;
      if (star.y < 0) star.y = height;
      if (star.y > height) star.y = 0;
    }
  }, [mouseInfluence, mouseGravity, gravityStrength, glowAnimation]);

  const draw = useCallback(
    (ctx: CanvasRenderingContext2D) => {
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
      for (const star of starsRef.current) {
        ctx.save();
        ctx.shadowColor = starsColor;
        ctx.shadowBlur = glowIntensity * star.glow * 2;
        ctx.globalAlpha = star.opacity;
        ctx.fillStyle = starsColor;
        ctx.beginPath();
        ctx.arc(star.x * dpr, star.y * dpr, star.size * dpr, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
      }
    },
    [starsColor, glowIntensity, dpr],
  );

  useEffect(() => {
    fit();
    const host = hostRef.current;
    const resizeObs = new ResizeObserver(fit);
    if (host) resizeObs.observe(host);
    const intersectObs = new IntersectionObserver(
      ([entry]) => {
        visibleRef.current = entry.isIntersecting;
      },
      { threshold: 0 },
    );
    if (host) intersectObs.observe(host);

    const loop = () => {
      const ctx = canvasRef.current?.getContext("2d");
      if (ctx && visibleRef.current) {
        step();
        draw(ctx);
      }
      rafRef.current = requestAnimationFrame(loop);
    };
    rafRef.current = requestAnimationFrame(loop);

    return () => {
      resizeObs.disconnect();
      intersectObs.disconnect();
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
    };
  }, [fit, step, draw]);

  const track = (clientX: number, clientY: number) => {
    const rect = canvasRef.current?.getBoundingClientRect();
    if (!rect) return;
    mouseRef.current = { x: clientX - rect.left, y: clientY - rect.top };
  };

  return (
    <div
      ref={hostRef}
      className={cn("relative size-full overflow-hidden", className)}
      onMouseMove={(e) => track(e.clientX, e.clientY)}
      onTouchMove={(e) => {
        const t = e.touches[0];
        if (t) track(t.clientX, t.clientY);
      }}
      onClick={(e) => {
        const rect = canvasRef.current?.getBoundingClientRect();
        if (rect) spawn(e.clientX - rect.left, e.clientY - rect.top);
      }}
    >
      <canvas ref={canvasRef} className="block h-full w-full" />
    </div>
  );
}

Update the import paths to match your project setup.

Similar components

Glow Wave Bars

Sine Flow Background

Max

Grain Concierge Landing

Max

Pixel Atelier Landing

Install via CLI

Resource details

PublishedJuly 17, 2026
CategoryHero
ReactCanvas 2DTailwind CSS