# Firefly Meadow

> Dusk over a meadow: tall grass sways against a fading sky while fireflies wander through it, glowing and fading on their own slow rhythms. They come to the cursor.

Category: Backgrounds · Free · Updated 2026-11-09 · Live demo: https://www.motionkitui.com/components/firefly-meadow

## When to use it

Summer campaigns, camping and outdoor brands, children's books and games, wedding and event pages, and calm, nostalgic storytelling.

## How it works

The sky is a gradient with a far tree line, and the grass is a few hundred blades, each a tapering pair of curves that bends with two slow sine waves, so the meadow ripples rather than moving in step. Fireflies wander on sums of slow sine waves, and each one's glow is a sine raised to a power, so they spend most of the time dark and then swell softly. One glow sprite is drawn once and stamped with additive blending, so they bloom where they overlap. Some fly behind the grass and some in front, and near the pointer they drift closer but keep their distance.

## Installation

```bash
npx shadcn@latest add https://www.motionkitui.com/r/firefly-meadow.json
```

Or copy `components/motionkit/firefly-meadow.tsx` below. Requires react and Tailwind CSS v4. Free for personal projects; commercial use needs MotionKit Plus (https://www.motionkitui.com/pricing).

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `colors` | `[string, string, string]` | `["#141A33", "#4B5A6E", "#070A0C"]` | The night above, the dusk at the horizon and the grass. |
| `glow` | `string` | `"#E9F59A"` | The fireflies' light. |
| `count` | `number` | `40` | Fireflies in the meadow. |
| `breeze` | `number` | `1` | Breeze in the grass. 0 for a still evening. |
| `interactive` | `boolean` | `true` | Let the fireflies drift towards the pointer. |
| `children` | `ReactNode` |  | Your content, layered above. |

## Accessibility

- **Keyboard: Not applicable.** Decorative, nothing to focus.
- **Screen readers: Pass.** The scene is hidden from assistive tech; only your content is read.
- **Reduced motion: Pass.** With reduced motion on, the meadow is drawn once with the fireflies softly lit and still. It also stops animating off screen.
- **Colour contrast: Pass.** Ivory text measures 15.2:1 against the night at the top and 6.2:1 at the dusk horizon, so headlines belong in the upper half.

## Source

```tsx
"use client";

import { useEffect, useRef, type ReactNode } from "react";

type FireflyMeadowProps = {
  children?: ReactNode;
  /** The dusk sky from top to horizon, then the grass silhouette. */
  colors?: [top: string, horizon: string, grass: string];
  /** Colour of the fireflies' glow. */
  glow?: string;
  /** Fireflies in the meadow. */
  count?: number;
  /** Breeze in the grass, 0 for a still evening. */
  breeze?: number;
  /** Let the fireflies drift curiously towards the pointer. */
  interactive?: boolean;
  className?: string;
};

// canvas colours must be plain values, so mixes are worked out here rather than in CSS
const rgb = (hex: string) => {
  const value = parseInt(hex.replace("#", "").padEnd(6, "0").slice(0, 6), 16);
  return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
};
const mix = (a: string, b: string, amount: number, alpha = 1) => {
  const [x, y] = [rgb(a), rgb(b)];
  const [r, g, bl] = x.map((channel, index) => Math.round(channel * amount + y[index] * (1 - amount)));
  return `rgba(${r}, ${g}, ${bl}, ${alpha})`;
};

type Fly = { x: number; y: number; seed: number; front: boolean; phase: number; rate: number; size: number; vx: number; vy: number };
type Blade = { x: number; height: number; lean: number; seed: number; width: number; shade: number };

/**
 * Dusk over a meadow. Tall grass sways against a fading sky and a far tree line, and fireflies wander through it,
 * glowing and fading on their own slow rhythms, some behind the grass and some in front. They come to the cursor.
 */
export function FireflyMeadow({
  children,
  colors = ["#141A33", "#4B5A6E", "#070A0C"],
  glow = "#E9F59A",
  count = 40,
  breeze = 1,
  interactive = true,
  className = "",
}: FireflyMeadowProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    const area = canvas?.parentElement;
    const context = canvas?.getContext("2d");
    if (!canvas || !area || !context) return;
    const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const [top, horizon, grass] = colors;

    let width = 0;
    let height = 0;
    let ratio = 1;
    let frame = 0;
    let visible = true;
    let last = 0;
    let time = 0;
    const pointer = { x: 0, y: 0, active: false };

    // seeded, so the meadow is laid out the same on every load
    let seed = 11;
    const random = () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646;
    let flies: Fly[] = [];
    let blades: Blade[] = [];
    let trees: number[] = [];

    // one soft glow, drawn once and stamped for every firefly
    const sprite = document.createElement("canvas");
    sprite.width = sprite.height = 64;
    const s = sprite.getContext("2d")!;
    const g = s.createRadialGradient(32, 32, 0, 32, 32, 32);
    g.addColorStop(0, "#ffffff");
    g.addColorStop(0.12, glow);
    g.addColorStop(0.35, mix(glow, glow, 1, 0.35));
    g.addColorStop(1, mix(glow, glow, 1, 0));
    s.fillStyle = g;
    s.fillRect(0, 0, 64, 64);

    function layout() {
      seed = 11;
      blades = Array.from({ length: Math.round(width / 3.2) }, () => ({
        x: random() * width,
        height: height * (0.12 + random() * random() * 0.3),
        lean: (random() - 0.5) * 0.5,
        seed: random() * 100,
        width: 1.2 + random() * 2.2,
        shade: random(),
      })).sort((a, b) => a.height - b.height);
      trees = Array.from({ length: 48 }, () => random());
      flies = Array.from({ length: count }, () => ({
        x: random() * width,
        y: height * (0.35 + random() * 0.55),
        seed: random() * 1000,
        front: random() > 0.55,
        phase: random() * Math.PI * 2,
        rate: 0.25 + random() * 0.5,
        size: 10 + random() * 16,
        vx: 0,
        vy: 0,
      }));
    }

    function resize() {
      const rect = canvas!.getBoundingClientRect();
      ratio = Math.min(window.devicePixelRatio || 1, 2);
      width = rect.width;
      height = rect.height;
      canvas!.width = Math.max(1, Math.round(width * ratio));
      canvas!.height = Math.max(1, Math.round(height * ratio));
      layout();
    }

    // a long, slow pulse: mostly dark, then a soft glow that swells and fades
    const brightness = (fly: Fly) => {
      const wave = Math.sin(time * fly.rate * 1.6 + fly.phase);
      return Math.pow(Math.max(0, wave), 3);
    };

    function drawFlies(front: boolean) {
      const c = context!;
      c.globalCompositeOperation = "lighter";
      for (const fly of flies) {
        if (fly.front !== front) continue;
        const b = still ? 0.4 + (fly.seed % 1) * 0.5 : brightness(fly);
        if (b < 0.02) continue;
        const size = fly.size * (front ? 1.25 : 0.8) * (0.7 + b * 0.5);
        c.globalAlpha = b * (front ? 1 : 0.7);
        c.drawImage(sprite, fly.x - size / 2, fly.y - size / 2, size, size);
      }
      c.globalCompositeOperation = "source-over";
      c.globalAlpha = 1;
    }

    function draw() {
      const c = context!;
      c.setTransform(ratio, 0, 0, ratio, 0, 0);
      // the sky, fading from dusk at the horizon to night above
      const sky = c.createLinearGradient(0, 0, 0, height);
      sky.addColorStop(0, top);
      sky.addColorStop(0.62, horizon);
      sky.addColorStop(1, horizon);
      c.fillStyle = sky;
      c.fillRect(0, 0, width, height);
      // the far tree line: overlapping rounded crowns, so it reads as woodland rather than mountains
      c.fillStyle = mix(grass, horizon, 0.7);
      c.fillRect(0, height * 0.66, width, height * 0.34);
      trees.forEach((value, index) => {
        const x = (index / (trees.length - 1)) * width * 1.1 - width * 0.05;
        const r = height * (0.035 + value * 0.05);
        c.beginPath();
        c.arc(x, height * 0.67 - r * 0.55, r, 0, Math.PI * 2);
        c.fill();
      });

      drawFlies(false);

      // the grass: each blade a tapering curve that sways with the breeze, nearer blades darker
      const sway = still ? 0 : time;
      for (const blade of blades) {
        const bend = blade.lean + Math.sin(sway * 1.1 + blade.x * 0.012 + blade.seed) * 0.12 * breeze + Math.sin(sway * 0.37) * 0.08 * breeze;
        const tipX = blade.x + bend * blade.height;
        const tipY = height - blade.height;
        c.fillStyle = mix(grass, horizon, 0.7 + blade.shade * 0.3);
        c.beginPath();
        c.moveTo(blade.x - blade.width, height);
        c.quadraticCurveTo(blade.x + bend * blade.height * 0.3, height - blade.height * 0.6, tipX, tipY);
        c.quadraticCurveTo(blade.x + bend * blade.height * 0.3 + blade.width, height - blade.height * 0.6, blade.x + blade.width, height);
        c.fill();
      }

      drawFlies(true);
    }

    function step(dt: number) {
      time += dt;
      for (const fly of flies) {
        // wandering: two slow sine waves per axis, different for every firefly
        const wx = Math.sin(time * 0.31 + fly.seed) + Math.sin(time * 0.17 + fly.seed * 2.3) * 0.6;
        const wy = Math.cos(time * 0.27 + fly.seed * 1.7) + Math.sin(time * 0.11 + fly.seed) * 0.5;
        let ax = wx * 9;
        let ay = wy * 6;
        if (pointer.active) {
          const dx = pointer.x - fly.x;
          const dy = pointer.y - fly.y;
          const distance = Math.hypot(dx, dy);
          // curious, not drawn in: they come nearer but keep a little distance
          if (distance < 220 && distance > 30) {
            ax += (dx / distance) * 22;
            ay += (dy / distance) * 22;
          }
        }
        fly.vx = fly.vx * 0.94 + ax * dt;
        fly.vy = fly.vy * 0.94 + ay * dt;
        fly.x += fly.vx * dt * 6;
        fly.y += fly.vy * dt * 6;
        // keep them over the meadow
        if (fly.x < -20) fly.x = width + 20;
        if (fly.x > width + 20) fly.x = -20;
        fly.y = Math.max(height * 0.25, Math.min(height - 6, fly.y));
      }
    }

    function loop(now: number) {
      const dt = last ? Math.min(0.05, (now - last) / 1000) : 0;
      last = now;
      step(dt);
      draw();
      frame = visible ? requestAnimationFrame(loop) : 0;
      if (!frame) last = 0;
    }

    resize();
    time = 4;
    draw();
    if (!still) frame = requestAnimationFrame(loop);
    const resizeObserver = new ResizeObserver(() => {
      resize();
      draw();
    });
    resizeObserver.observe(canvas);
    const visibilityObserver = new IntersectionObserver(([entry]) => {
      visible = entry.isIntersecting;
      if (visible && !frame && !still) frame = requestAnimationFrame(loop);
    });
    visibilityObserver.observe(canvas);

    function move(event: PointerEvent) {
      if (!interactive || still) return;
      const rect = canvas!.getBoundingClientRect();
      pointer.x = event.clientX - rect.left;
      pointer.y = event.clientY - rect.top;
      pointer.active = true;
    }
    const leave = () => (pointer.active = false);
    area.addEventListener("pointermove", move);
    area.addEventListener("pointerleave", leave);

    return () => {
      cancelAnimationFrame(frame);
      resizeObserver.disconnect();
      visibilityObserver.disconnect();
      area.removeEventListener("pointermove", move);
      area.removeEventListener("pointerleave", leave);
    };
    // the colours are compared by value, so a new array with the same colours doesn't restart it
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [colors.join(), glow, count, breeze, interactive]);

  return (
    <div className={`relative isolate overflow-hidden ${className}`} style={{ background: `linear-gradient(to bottom, ${colors[0]}, ${colors[1]})` }}>
      <canvas ref={canvasRef} aria-hidden className="pointer-events-none absolute inset-0 -z-10 size-full" />
      {children}
    </div>
  );
}
```
