# Dappled Light

> Sunlight through leaves on a warm wall: soft round spots of sun open and close as the canopy sways, and leaf shadows drift across. Komorebi, in a shader.

Category: Backgrounds · Free · Updated 2026-11-10 · Live demo: https://www.motionkitui.com/components/dappled-light

## When to use it

Interiors, architecture and furniture brands, cafés and bakeries, skincare and wellness, and slow-living or journal-style sites that want warmth.

## How it works

Sun falling through a gap in leaves lands as a round spot, because each gap acts as a pinhole camera for the sun. The shader recreates that with a grid of soft discs, one per cell at a random size and position, each jittering gently. Whether a disc shows depends on a canopy: fractal noise that sways as a whole and flutters in parts, so spots open and close as the leaves move. Broad, blurry shadows of nearer leaves drift over the top, a faint fringe warms the edges of each spot, and the pointer pushes the leaves aside as if brushed.

## Installation

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

Or copy `components/motionkit/dappled-light.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]` | `["#3B2F27", "#FFD9A0"]` | The wall in shade and the sunlight on it. |
| `breeze` | `number` | `1` | Wind in the leaves. 0 holds them still. |
| `light` | `number` | `0.5` | How much of the wall the sun reaches, 0 to 1. |
| `scale` | `number` | `1` | Size of the patches; lower is larger and softer. |
| `interactive` | `boolean` | `true` | Let the pointer brush the leaves aside. |
| `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 light is drawn once and holds still. It also stops rendering off screen.
- **Colour contrast: Partial.** Ivory text measures 11.5:1 on the shade but only 1.2:1 on a patch of sun, and the patches move. Put text on a dark backing, as the demo does, or keep the light setting low.

## Source

```tsx
"use client";

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

type DappledLightProps = {
  children?: ReactNode;
  /** The wall in shade, then the warm sunlight that falls on it. */
  colors?: [shade: string, sun: string];
  /** Strength of the breeze in the leaves. 0 holds them still. */
  breeze?: number;
  /** How much of the wall the sun reaches, 0 to 1. */
  light?: number;
  /** Size of the patches of light: lower is larger and softer. */
  scale?: number;
  /** Let the leaves lean away from the pointer, as if brushed. */
  interactive?: boolean;
  className?: string;
};

const vertex = `attribute vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }`;

// komorebi: sunlight through gaps in leaves lands as soft round spots (each gap is a pinhole), and the canopy
// swaying overhead decides which gaps are open. Large leaf shadows drift across in a second, blurrier layer.
const fragment = `
precision highp float;
uniform vec2 res; uniform float time; uniform vec3 pointer; uniform vec3 shade; uniform vec3 sun;
uniform float light; uniform float scale;
float hash(vec2 p) { p = fract(p * vec2(233.34, 851.73)); p += dot(p, p + 23.45); return fract(p.x * p.y); }
vec2 hash2(vec2 p) { return vec2(hash(p), hash(p + 17.31)); }
float noise(vec2 p) {
  vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
  return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y);
}
float fbm(vec2 p) { float v = 0.0; float a = 0.5; for (int i = 0; i < 4; i++) { v += a * noise(p); p *= 2.1; a *= 0.5; } return v; }
// the canopy: open (1) where the leaves part, closed (0) where they overlap; it sways as a whole and flutters in parts
float canopy(vec2 p, float t) {
  vec2 sway = vec2(sin(t * 0.6) * 0.18 + sin(t * 1.7) * 0.05, cos(t * 0.45) * 0.1);
  float n = fbm(p * 1.3 + sway + fbm(p * 2.0 + t * 0.15) * 0.35);
  return smoothstep(0.62 - light * 0.36, 0.7 - light * 0.3, n);
}
void main() {
  vec2 uv = (gl_FragCoord.xy - 0.5 * res) / min(res.x, res.y);
  vec2 d = uv - pointer.xy;
  vec2 brush = d * pointer.z * exp(-dot(d, d) * 6.0) * 0.25;
  float t = time;
  vec2 p = uv * scale * 3.0 + brush * 3.0;

  // spots of sun: one soft disc per cell, sized and placed at random, lit only where the canopy above is open
  float spots = 0.0;
  vec2 cell = floor(p * 1.4);
  for (int y = -1; y <= 1; y++) {
    for (int x = -1; x <= 1; x++) {
      vec2 c = cell + vec2(float(x), float(y));
      vec2 h = hash2(c);
      vec2 jitter = vec2(sin(t * (0.5 + h.x) + h.y * 6.3), cos(t * (0.4 + h.y) + h.x * 6.3)) * 0.05;
      vec2 centre = (c + 0.15 + h * 0.7) / 1.4 + jitter;
      float radius = 0.1 + h.y * 0.22;
      float gap = canopy(centre * 0.9, t);
      // soft edges, slightly oval like sun spots on a wall
      float disc = smoothstep(radius, radius * 0.15, length((p - centre) * vec2(1.0, 1.25)));
      spots += disc * gap * (0.7 + h.x * 0.3);
    }
  }
  spots = min(spots, 1.0);
  // where the canopy thins, a broad warm glow spills over the wall as well
  float glow = canopy(p * 0.5 + 3.7, t * 0.8) * 0.3;
  // broad, blurry shadows of the nearer leaves drift over everything
  float near = smoothstep(0.35, 0.75, fbm(p * 0.45 + vec2(t * 0.05, -t * 0.03) + brush));
  // a soft wash of bounced light so the shade is never flat
  float wash = fbm(p * 0.6 - t * 0.02) * 0.25;

  vec3 col = shade * (1.0 + wash);
  vec3 warm = sun * (1.0 + spots * 0.15);
  col = mix(col, warm, clamp(spots + glow * 0.5, 0.0, 1.0) * (1.0 - near * 0.6) * 0.9);
  // the edges of each spot catch a faint warm fringe, as real sun spots do
  col += sun * smoothstep(0.05, 0.4, spots) * smoothstep(0.85, 0.4, spots) * 0.12;
  col *= 1.0 - smoothstep(0.6, 1.5, length(uv * vec2(0.75, 1.0))) * 0.35;
  col += (hash(gl_FragCoord.xy + fract(t)) - 0.5) * 0.03;
  gl_FragColor = vec4(col, 1.0);
}`;

const toVec = (hex: string) => {
  const value = parseInt(hex.replace("#", "").padEnd(6, "0").slice(0, 6), 16);
  return [((value >> 16) & 255) / 255, ((value >> 8) & 255) / 255, (value & 255) / 255];
};

/*
 * WebGL starts on the visitor's first move, touch, scroll or key press rather than on load, with the still fallback
 * until then. Without a GPU, browsers draw WebGL on the CPU and creating the first context can freeze the page for
 * seconds, so where WebGPU reports only a software adapter, the shader never starts at all. The wait also keeps the
 * shader's set-up off the page's first load, when the browser is busiest.
 */
type GpuProbe = { requestAdapter: () => Promise<{ isFallbackAdapter?: boolean; info?: { isFallbackAdapter?: boolean } } | null> };
let gpuReady: Promise<boolean> | undefined;
function whenGpuReady() {
  return (gpuReady ??= (async () => {
    await new Promise<void>((resolve) => {
      const events = ["pointermove", "pointerdown", "keydown", "wheel", "touchstart", "scroll"] as const;
      const start = () => {
        events.forEach((name) => window.removeEventListener(name, start));
        resolve();
      };
      events.forEach((name) => window.addEventListener(name, start, { passive: true }));
    });
    const gpu = (navigator as Navigator & { gpu?: GpuProbe }).gpu;
    const adapter = gpu ? await gpu.requestAdapter().catch(() => null) : null;
    return !(adapter?.isFallbackAdapter || adapter?.info?.isFallbackAdapter);
  })());
}

/**
 * Sunlight falling through leaves onto a warm wall, the light the Japanese call komorebi. Soft round spots of sun
 * open and close as the canopy sways, broad leaf shadows drift across, and brushing the pointer through stirs them.
 */
export function DappledLight({
  children,
  colors = ["#3B2F27", "#FFD9A0"],
  breeze = 1,
  light = 0.5,
  scale = 1,
  interactive = true,
  className = "",
}: DappledLightProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  // a fresh canvas means a fresh WebGL context, for when the browser has taken this one back
  const [generation, setGeneration] = useState(0);
  // false until it's sensible to start WebGL (see whenGpuReady)
  const [gpu, setGpu] = useState(false);
  useEffect(() => {
    let live = true;
    whenGpuReady().then((ready) => {
      if (live && ready) setGpu(true);
    });
    return () => {
      live = false;
    };
  }, []);

  // hand the context back when this canvas is done with (unmounted, hidden or replaced) rather than whenever the
  // browser gets round to it: browsers allow only about 16 at once and destroy the oldest beyond that
  useEffect(() => {
    const canvas = canvasRef.current;
    // only if a context was made: asking for one here would create it
    return () => {
      if (canvas?.dataset.gl) canvas.getContext("webgl")?.getExtension("WEBGL_lose_context")?.loseContext();
    };
  }, [generation]);

  useEffect(() => {
    const canvas = canvasRef.current;
    const area = canvas?.parentElement;
    if (!gpu) return;
    const gl = canvas?.getContext("webgl", { antialias: false, premultipliedAlpha: false });
    if (!canvas || !area || !gl) return;
    canvas.dataset.gl = "1";
    // with no GPU, WebGL runs on the CPU: compiling the shader alone can block the page for most of a second, and every
    // frame after that, so software renderers get the still fallback instead
    const renderer = gl.getExtension("WEBGL_debug_renderer_info");
    if (renderer && /swiftshader|llvmpipe|softpipe|software/i.test(String(gl.getParameter(renderer.UNMASKED_RENDERER_WEBGL)))) return;
    // a lost context never draws again, so start over on a new canvas (a few times at most)
    if (gl.isContextLost()) {
      const retry = requestAnimationFrame(() => setGeneration((count) => (count < 8 ? count + 1 : count)));
      return () => cancelAnimationFrame(retry);
    }
    const onLost = (event: Event) => {
      event.preventDefault();
      setGeneration((count) => (count < 8 ? count + 1 : count));
    };
    canvas.addEventListener("webglcontextlost", onLost);
    const still = breeze === 0 || window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    const compile = (type: number, source: string) => {
      const shader = gl.createShader(type)!;
      gl.shaderSource(shader, source);
      gl.compileShader(shader);
      return shader;
    };
    const program = gl.createProgram()!;
    const shaders = [compile(gl.VERTEX_SHADER, vertex), compile(gl.FRAGMENT_SHADER, fragment)];
    shaders.forEach((shader) => gl.attachShader(program, shader));
    gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return;
    gl.useProgram(program);
    const buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
    const position = gl.getAttribLocation(program, "p");
    gl.enableVertexAttribArray(position);
    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
    const uniform = (name: string) => gl.getUniformLocation(program, name);
    const u = { res: uniform("res"), time: uniform("time"), pointer: uniform("pointer") };
    gl.uniform3fv(uniform("shade"), toVec(colors[0]));
    gl.uniform3fv(uniform("sun"), toVec(colors[1]));
    gl.uniform1f(uniform("light"), Math.max(0, Math.min(1, light)));
    gl.uniform1f(uniform("scale"), scale);

    let frame = 0;
    let visible = true;
    let elapsed = 0;
    let last = 0;
    const pointer = { x: 0, y: 0, strength: 0, target: 0 };

    function resize() {
      const rect = canvas!.getBoundingClientRect();
      // the light is soft, so a reduced resolution looks the same
      const ratio = Math.min(window.devicePixelRatio || 1, 2) * 0.6;
      canvas!.width = Math.max(1, Math.round(rect.width * ratio));
      canvas!.height = Math.max(1, Math.round(rect.height * ratio));
      gl!.viewport(0, 0, canvas!.width, canvas!.height);
      gl!.uniform2f(u.res, canvas!.width, canvas!.height);
    }

    function draw(time: number) {
      elapsed += last ? Math.min(0.05, (time - last) / 1000) * breeze : 0;
      last = time;
      pointer.strength += (pointer.target - pointer.strength) * 0.04;
      gl!.uniform1f(u.time, elapsed + 3);
      gl!.uniform3f(u.pointer, pointer.x, pointer.y, pointer.strength);
      gl!.drawArrays(gl!.TRIANGLES, 0, 3);
    }

    function loop(time: number) {
      draw(time);
      frame = visible ? requestAnimationFrame(loop) : 0;
      if (!frame) last = 0;
    }

    resize();
    draw(0);
    if (!still) frame = requestAnimationFrame(loop);
    const resizeObserver = new ResizeObserver(() => {
      resize();
      draw(performance.now());
    });
    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 || event.pointerType === "touch") return;
      const rect = canvas!.getBoundingClientRect();
      const size = Math.min(rect.width, rect.height);
      pointer.x = (event.clientX - rect.left - rect.width / 2) / size;
      pointer.y = -(event.clientY - rect.top - rect.height / 2) / size;
      pointer.target = 1;
    }
    const leave = () => (pointer.target = 0);
    area.addEventListener("pointermove", move);
    area.addEventListener("pointerleave", leave);

    return () => {
      cancelAnimationFrame(frame);
      resizeObserver.disconnect();
      visibilityObserver.disconnect();
      area.removeEventListener("pointermove", move);
      area.removeEventListener("pointerleave", leave);
      gl.deleteBuffer(buffer);
      shaders.forEach((shader) => gl.deleteShader(shader));
      gl.deleteProgram(program);
      canvas.removeEventListener("webglcontextlost", onLost);
    };
    // 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(), breeze, light, scale, interactive, generation, gpu]);

  return (
    <div
      className={`relative isolate overflow-hidden ${className}`}
      // shown only if WebGL is unavailable: the wall with a few still patches of sun
      style={{ backgroundColor: colors[0], backgroundImage: `radial-gradient(circle at 30% 35%, color-mix(in oklab, ${colors[1]} 55%, transparent) 0 6%, transparent 9%), radial-gradient(circle at 68% 58%, color-mix(in oklab, ${colors[1]} 45%, transparent) 0 5%, transparent 8%)` }}
    >
      <canvas key={generation} ref={canvasRef} aria-hidden className="absolute inset-0 -z-10 size-full" />
      {children}
    </div>
  );
}
```
