pstzx

Terrain Contour

Shaders 5

About

Topographic Contour Surface is an interactive digital topographic atlas that transforms elevation data and terraced terrain morphology into a living, real-time halftone dot matrix.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Terrain Contour to your project and fits it to your theme.

Code

How Terrain Contour is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

import React, { useEffect, useRef, useState } from 'react';

/**
 * TOPOGRAPHIC CONTOUR SURFACE — EDITORIAL LANDING ENGINE
 * A responsive single-file React component featuring a real-time
 * halftone topographic contour canvas with outward radial wave propagation,
 * vertical edge dot attenuation, and interactive cursor ripple distortion.
 */

export default function App() {
  const canvasRef = useRef(null);
  const [elevation, setElevation] = useState(240);

  // Mutable animation & pointer state stored in refs to avoid React re-renders per frame
  const stateRef = useRef({
    width: 0,
    height: 0,
    dpr: 1,
    time: 0,
    lastTimestamp: 0,
    pointerX: -9999,
    pointerY: -9999,
    smoothPointerX: -9999,
    smoothPointerY: -9999,
    pointerActive: false,
    seismicBoost: 0,
    lastReportedElev: 240,
  });

  // Trigger a temporary seismic wave pulse
  const handleTriggerPulse = () => {
    stateRef.current.seismicBoost = 1.0;
  };

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d', { alpha: false });
    if (!ctx) return;

    // Inject editorial fonts dynamically for standalone preview fidelity
    const fontLinkId = 'topo-editorial-fonts';
    if (!document.getElementById(fontLinkId)) {
      const link = document.createElement('link');
      link.id = fontLinkId;
      link.rel = 'stylesheet';
      link.href =
        'https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,500;0,600;1,500&family=Plus+Jakarta+Sans:wght@300;400;500;600&family=Space+Mono:wght@400;700&display=swap';
      document.head.appendChild(link);
    }

    const resizeCanvas = () => {
      const state = stateRef.current;
      const rect = canvas.parentElement
        ? canvas.parentElement.getBoundingClientRect()
        : { width: window.innerWidth, height: window.innerHeight };

      state.dpr = Math.min(window.devicePixelRatio || 1, 2);
      state.width = Math.max(1, rect.width || window.innerWidth);
      state.height = Math.max(1, rect.height || window.innerHeight);

      canvas.width = Math.floor(state.width * state.dpr);
      canvas.height = Math.floor(state.height * state.dpr);
      ctx.setTransform(state.dpr, 0, 0, state.dpr, 0, 0);
    };

    const updatePointer = (x, y) => {
      const state = stateRef.current;
      state.pointerX = x;
      state.pointerY = y;
      if (!state.pointerActive) {
        state.smoothPointerX = x;
        state.smoothPointerY = y;
        state.pointerActive = true;
      }
    };

    const handleMouseMove = (e) => {
      updatePointer(e.clientX, e.clientY);
    };

    const handleTouchMove = (e) => {
      if (e.touches && e.touches.length > 0) {
        updatePointer(e.touches[0].clientX, e.touches[0].clientY);
      }
    };

    const handleMouseLeave = () => {
      stateRef.current.pointerActive = false;
    };

    window.addEventListener('resize', resizeCanvas);
    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('touchmove', handleTouchMove, { passive: true });
    window.addEventListener('mouseleave', handleMouseLeave);

    resizeCanvas();

    // Compute responsive center & scale so the contour surface balances with editorial typography
    const getContourLayout = (w, h) => {
      if (w >= 1024) {
        return {
          cx: w * 0.65,
          cy: h * 0.49,
          scale: Math.min(w * 0.34, h * 0.44),
        };
      } else if (w >= 768) {
        return {
          cx: w * 0.68,
          cy: h * 0.48,
          scale: Math.min(w * 0.32, h * 0.40),
        };
      } else {
        return {
          cx: w * 0.50,
          cy: h * 0.35,
          scale: Math.min(w * 0.44, h * 0.28),
        };
      }
    };

    /**
     * Computes organically distorted radial distance forming terraced terrain indentations
     * paired with continuous outward radial wave propagation.
     */
    const getOrganicContourRadius = (nx, ny, t, boost) => {
      const rx = nx * 1.04;
      const ry = ny * 0.96;

      const r = Math.hypot(rx, ry);
      const theta = Math.atan2(ry, rx);

      // Characteristic valley indentation on the bottom-left quadrant (~132 deg / 2.31 rad)
      let dTheta = theta - 2.31;
      while (dTheta > Math.PI) dTheta -= Math.PI * 2;
      while (dTheta < -Math.PI) dTheta += Math.PI * 2;

      const indent = 0.165 * Math.exp(-Math.pow(dTheta / 0.44, 2));
      const upperLobe = 0.045 * Math.cos(theta * 2.0 + 0.55 + Math.sin(t * 0.8) * 0.12);
      const sideWave = 0.025 * Math.sin(theta * 3.0 - 0.4 - t * 0.6);

      // Outward radial wave propagating smoothly from center toward outer boundary
      const amp = 0.022 + boost * 0.030;
      const outwardRipple = amp * Math.sin(r * 14.0 - t * 2.8) * Math.min(1, r * 2.5);

      return r + indent - upperLobe - sideWave - outwardRipple;
    };

    /**
     * Evaluates halftone dot density at each grid coordinate (px, py),
     * generating 4 layered elevation contour rings separated by clean gaps.
     */
    const evaluateUnifiedField = (px, py, cx, cy, scale, t) => {
      const state = stateRef.current;
      let nx = (px - cx) / scale;
      let ny = (py - cy) / scale;

      // Cursor interaction: creates concentric ripple waves when approaching the contour
      let cursorWaveOffset = 0;
      if (state.pointerActive) {
        const dxp = px - state.smoothPointerX;
        const dyp = py - state.smoothPointerY;
        const distP = Math.hypot(dxp, dyp);
        const influenceRadius = scale * 0.72;
        if (distP < influenceRadius) {
          const falloff = Math.pow(1 - distP / influenceRadius, 2);
          const ripple = Math.sin(distP * 0.14 - t * 9.5) * falloff;
          cursorWaveOffset = ripple * 0.048;

          const radialPush = falloff * (0.045 + 0.025 * Math.sin(distP * 0.1 - t * 8.0));
          nx -= (dxp / (distP + 1)) * radialPush;
          ny -= (dyp / (distP + 1)) * radialPush;
        }
      }

      const d = getOrganicContourRadius(nx, ny, t, state.seismicBoost) + cursorWaveOffset;

      // 1. Clean central summit basin without dots
      const innerHoleRadius = 0.255 + (0.012 + state.seismicBoost * 0.016) * Math.sin(t * 2.8);
      if (d < innerHoleRadius) {
        return -1.0;
      }

      // 2. Four terraced contour elevation rings with clear spacing gaps
      const ringSpecs = [
        { center: 0.345, halfWidth: 0.068, peak: 1.00 },
        { center: 0.515, halfWidth: 0.062, peak: 0.84 },
        { center: 0.680, halfWidth: 0.056, peak: 0.66 },
        { center: 0.845, halfWidth: 0.052, peak: 0.48 },
      ];

      let maxRingVal = 0;
      const waveAmp = 0.016 + state.seismicBoost * 0.024;

      for (let i = 0; i < ringSpecs.length; i++) {
        const ring = ringSpecs[i];
        const phaseShift = waveAmp * Math.sin(t * 2.8 - i * 1.15);
        const dynamicCenter = ring.center + phaseShift;
        const dynamicHalfWidth = ring.halfWidth * (1 + 0.08 * Math.sin(t * 2.8 - i * 1.15));

        const distFromRing = Math.abs(d - dynamicCenter);
        if (distFromRing < dynamicHalfWidth) {
          const norm = distFromRing / dynamicHalfWidth;
          const profile = Math.pow(Math.cos(norm * Math.PI * 0.5), 1.35);
          const pulsePeak = ring.peak * (0.92 + 0.08 * Math.sin(t * 2.8 - i * 1.15));
          maxRingVal = Math.max(maxRingVal, pulsePeak * profile);
        }
      }

      // 3. Subtle outer lowland halo
      if (d >= 0.88 && d < 1.24) {
        const outerWave = 0.5 + 0.5 * Math.sin(d * 18.0 - t * 2.8);
        const haloFade = (0.08 + 0.08 * outerWave) * Math.exp(-Math.pow((d - 0.88) / 0.16, 2));
        maxRingVal = Math.max(maxRingVal, haloFade);
      }

      return Math.max(0, Math.min(1, maxRingVal));
    };

    const render = () => {
      const state = stateRef.current;
      const { width: w, height: h, time: t } = state;
      if (w <= 0 || h <= 0) return;

      ctx.fillStyle = '#F3F1EC';
      ctx.fillRect(0, 0, w, h);

      const { cx, cy, scale } = getContourLayout(w, h);
      const spacing = Math.max(5.5, scale / 34);

      const minRadius = Math.max(0.55, spacing * 0.075);
      const maxRadius = spacing * 0.69;

      // Vertical fade zones (top & bottom) to keep header and footer clean
      const topFadeEnd = h * 0.24;
      const bottomFadeStart = h * 0.76;

      ctx.fillStyle = '#191E12';
      ctx.beginPath();

      const startCol = Math.floor(-cx / spacing) - 1;
      const endCol = Math.ceil((w - cx) / spacing) + 1;
      const startRow = Math.floor(-cy / spacing) - 1;
      const endRow = Math.ceil((h - cy) / spacing) + 1;

      for (let r = startRow; r <= endRow; r++) {
        const py = cy + r * spacing;

        // Smoothstep vertical attenuation at top and bottom margins
        let verticalFade = 1.0;
        if (py < topFadeEnd) {
          const normY = Math.max(0, Math.min(1, py / topFadeEnd));
          verticalFade = normY * normY * (3 - 2 * normY);
        } else if (py > bottomFadeStart) {
          const normY = Math.max(0, Math.min(1, (h - py) / (h - bottomFadeStart)));
          verticalFade = normY * normY * (3 - 2 * normY);
        }

        if (verticalFade <= 0.01) continue;

        for (let c = startCol; c <= endCol; c++) {
          const px = cx + c * spacing;
          const val = evaluateUnifiedField(px, py, cx, cy, scale, t);

          if (val < 0) continue;

          const baseRadius = minRadius + Math.pow(val, 1.12) * (maxRadius - minRadius);
          const radius = baseRadius * verticalFade;

          if (radius > 0.15) {
            ctx.moveTo(px + radius, py);
            ctx.arc(px, py, radius, 0, Math.PI * 2);
          }
        }
      }

      ctx.fill();

      // Subtle cartographic reticle around active cursor
      if (state.pointerActive) {
        ctx.save();
        ctx.strokeStyle = 'rgba(25, 30, 18, 0.28)';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.arc(state.smoothPointerX, state.smoothPointerY, 16, 0, Math.PI * 2);
        ctx.moveTo(state.smoothPointerX - 24, state.smoothPointerY);
        ctx.lineTo(state.smoothPointerX - 10, state.smoothPointerY);
        ctx.moveTo(state.smoothPointerX + 10, state.smoothPointerY);
        ctx.lineTo(state.smoothPointerX + 24, state.smoothPointerY);
        ctx.moveTo(state.smoothPointerX, state.smoothPointerY - 24);
        ctx.lineTo(state.smoothPointerX, state.smoothPointerY - 10);
        ctx.moveTo(state.smoothPointerX, state.smoothPointerY + 10);
        ctx.lineTo(state.smoothPointerX, state.smoothPointerY + 24);
        ctx.stroke();
        ctx.restore();
      }
    };

    let animationFrameId = 0;

    const animate = (timestamp) => {
      const state = stateRef.current;
      if (!state.lastTimestamp) state.lastTimestamp = timestamp;
      const dt = Math.min((timestamp - state.lastTimestamp) / 1000, 0.05);
      state.lastTimestamp = timestamp;

      state.time += dt;

      if (state.seismicBoost > 0.001) {
        state.seismicBoost *= Math.pow(0.25, dt);
      } else {
        state.seismicBoost = 0;
      }

      if (state.pointerActive) {
        state.smoothPointerX += (state.pointerX - state.smoothPointerX) * Math.min(1, dt * 8);
        state.smoothPointerY += (state.pointerY - state.smoothPointerY) * Math.min(1, dt * 8);

        const { cx, cy, scale } = getContourLayout(state.width, state.height);
        const distNorm = Math.hypot(state.smoothPointerX - cx, state.smoothPointerY - cy) / scale;
        const nextElev = Math.max(15, Math.round(400 - Math.min(1.2, distNorm) * 320));
        if (nextElev !== state.lastReportedElev) {
          state.lastReportedElev = nextElev;
          setElevation(nextElev);
        }
      }

      render();
      animationFrameId = requestAnimationFrame(animate);
    };

    animationFrameId = requestAnimationFrame(animate);

    return () => {
      cancelAnimationFrame(animationFrameId);
      window.removeEventListener('resize', resizeCanvas);
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('touchmove', handleTouchMove);
      window.removeEventListener('mouseleave', handleMouseLeave);
    };
  }, []);

  return (
    <div
      className="relative w-full h-screen overflow-hidden bg-[#F3F1EC] text-[#191E12] select-none"
      style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}
    >
      <style>{`
        .font-serif-editorial {
          font-family: 'Cormorant Garamond', Georgia, serif;
        }
        .font-mono-tech {
          font-family: 'Space Mono', monospace;
        }
        .topo-hairline {
          border-color: rgba(25, 30, 18, 0.14);
        }
        @keyframes slowSpin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
        .animate-reticle {
          animation: slowSpin 24s linear infinite;
        }
      `}</style>

      {/* Primary Canvas: Topographic Contour Surface */}
      <div className="absolute inset-0 z-0">
        <canvas ref={canvasRef} className="block w-full h-full" />
      </div>

      {/* Architectural Cartographic Frame & Editorial Layout */}
      <div className="relative z-10 flex flex-col justify-between w-full h-full p-4 sm:p-7 md:p-10 pointer-events-none">
        {/* 1. Minimalist Header Row with Precision Hairline */}
        <header className="flex items-center justify-between w-full pb-3.5 sm:pb-4 border-b topo-hairline">
          <div className="flex items-center gap-3 pointer-events-auto">
            {/* Micro Cartographic Compass Icon */}
            <svg
              className="w-4 h-4 text-[#191E12] animate-reticle"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
            >
              <circle cx="12" cy="12" r="9" strokeDasharray="2 2" />
              <path d="M12 2v4M12 18v4M2 12h4M18 12h4" />
            </svg>
            <span className="font-mono-tech text-xs sm:text-[13px] tracking-[0.26em] uppercase font-bold">
              TERRAIN CONTOUR
            </span>
          </div>

          {/* Center Navigation with Active Indicator */}
          <nav className="hidden lg:flex items-center gap-10 font-mono-tech text-[11px] tracking-[0.2em] uppercase text-[#191E12]/65 pointer-events-auto">
            <a href="#surface" className="text-[#191E12] font-bold flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full bg-[#191E12]" />
              Surface 01
            </a>
            <a href="#morphology" className="hover:text-[#191E12] transition-colors">
              Morphology
            </a>
            <a href="#elevation" className="hover:text-[#191E12] transition-colors">
              Elevation &amp; Gradient
            </a>
          </nav>

          {/* Top-Right Survey Coordinates */}
          <div className="flex items-center gap-4 font-mono-tech text-[10px] sm:text-[11px] tracking-wider text-[#191E12]/75">
            <span className="hidden sm:inline-block px-2 py-0.5 rounded border topo-hairline bg-[#F3F1EC]/70 backdrop-blur-sm">
              SCALE 1:25,000
            </span>
            <span className="font-bold">06°14&apos;S 106°59&apos;E</span>
          </div>
        </header>

        {/* 2. Main Area: Asymmetric Editorial Composition */}
        <main className="grid grid-cols-1 md:grid-cols-12 items-center md:items-end w-full my-auto md:my-0 gap-6">
          {/* Left Column: Editorial Typography & Controls */}
          <div className="md:col-span-6 lg:col-span-5 flex flex-col justify-between bg-[#F3F1EC]/75 md:bg-transparent backdrop-blur-md md:backdrop-blur-none border md:border-0 topo-hairline rounded-2xl p-5 sm:p-6 md:p-0 pointer-events-auto">
            {/* Metadata Tag */}
            <div className="flex items-center gap-3 mb-3 sm:mb-4">
              <span className="font-mono-tech text-[10px] uppercase tracking-[0.25em] text-[#191E12]/60">
                DIGITAL TOPOGRAPHIC ATLAS
              </span>
              <span className="h-[1px] w-8 bg-[#191E12]/25" />
            </div>

            {/* High-Contrast Display Headline */}
            <h1 className="text-3xl sm:text-4xl lg:text-[52px] font-light tracking-tight leading-[1.06] text-[#191E12]">
              Topographic
              <span className="block font-serif-editorial italic font-medium text-4xl sm:text-5xl lg:text-[60px] text-[#191E12] mt-0.5">
                Contour Surface
              </span>
            </h1>

            {/* Concise Editorial Description */}
            <p className="mt-4 sm:mt-5 text-xs sm:text-sm leading-relaxed text-[#191E12]/75 max-w-sm font-normal">
              A visual exploration of radial elevation wave propagation and terraced terrain morphology rendered through layered halftone dot matrices in real time.
            </p>

            {/* Action Row & Live Elevation Telemetry */}
            <div className="mt-6 sm:mt-8 flex flex-wrap items-center gap-4">
              <button
                type="button"
                onClick={handleTriggerPulse}
                className="group relative inline-flex items-center gap-3 px-5 py-3 rounded-full bg-[#191E12] text-[#F3F1EC] hover:bg-[#2A321E] active:scale-[0.98] transition-all text-xs font-mono-tech tracking-[0.16em] uppercase cursor-pointer shadow-sm"
              >
                <span>Trigger Pulse</span>
                <svg
                  className="w-3.5 h-3.5 transition-transform duration-300 group-hover:translate-x-0.5"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                >
                  <circle cx="12" cy="12" r="3" />
                  <circle cx="12" cy="12" r="8" strokeDasharray="3 3" />
                </svg>
              </button>

              {/* Live Cursor Telemetry Readout */}
              <div className="flex items-center gap-2.5 px-3.5 py-2 rounded-full border topo-hairline bg-[#F3F1EC]/80 backdrop-blur-sm">
                <span className="w-1.5 h-1.5 rounded-full bg-[#191E12] animate-ping" />
                <span className="font-mono-tech text-[11px] tracking-wider text-[#191E12] font-bold">
                  ELEV +{elevation}m
                </span>
              </div>
            </div>
          </div>

          {/* Right Column: Open Breathing Space for the Contour Surface */}
          <div className="hidden md:flex md:col-span-6 lg:col-span-7 flex-col items-end justify-end h-full">
            {/* Minimalist Cartographic Density Legend Card */}
            <div className="bg-[#F3F1EC]/80 backdrop-blur-md border topo-hairline rounded-2xl p-4 w-64 pointer-events-auto">
              <div className="flex items-center justify-between mb-2.5 pb-2 border-b topo-hairline">
                <span className="font-mono-tech text-[10px] uppercase tracking-[0.2em] text-[#191E12]/65">
                  DENSITY INDEX
                </span>
                <span className="font-mono-tech text-[10px] font-bold">4 LAYERS</span>
              </div>
              <div className="flex items-center justify-between gap-2">
                <div className="flex items-center gap-2">
                  <span className="w-1.5 h-1.5 rounded-full bg-[#191E12]/30" />
                  <span className="w-2 h-2 rounded-full bg-[#191E12]/55" />
                  <span className="w-2.5 h-2.5 rounded-full bg-[#191E12]/80" />
                  <span className="w-3 h-3 rounded-full bg-[#191E12]" />
                </div>
                <span className="font-mono-tech text-[11px] text-[#191E12]/80">0m — 400m</span>
              </div>
            </div>
          </div>
        </main>

        {/* 3. Precision Footer with Corner Markers */}
        <footer className="flex items-center justify-between w-full pt-3.5 border-t topo-hairline font-mono-tech text-[10px] sm:text-[11px] tracking-[0.18em] uppercase text-[#191E12]/65">
          <div className="flex items-center gap-2">
            <span>+</span>
            <span>WGS-84 DATUM // 25M INTERVAL</span>
          </div>
          <div className="hidden sm:block">MOVE CURSOR TO INTERACT WITH TERRAIN</div>
          <div className="flex items-center gap-2">
            <span>MORPHOLOGY STUDIO</span>
            <span>+</span>
          </div>
        </footer>
      </div>
    </div>
  );
}

More by pstzx

View all
  • Button Payment

    Button Payment

    109
  • Contour Land Map

    Contour Land Map

    29
  • Sign In Water Effect Glass

    Sign In Water Effect Glass

    26
  • Contour line Mountain

    Contour line Mountain

    22
  • Card Dashboard Analytic

    Card Dashboard Analytic

    12
  • Loading Screen Glass

    Loading Screen Glass

    12
  • 21 st Contour Line

    21 st Contour Line

    12
  • Contour line map

    Contour line map

    11

More in Shaders

View all
  • Glass Fold

    Glass Fold

    493
  • Shader Animation

    Shader Animation

    3.9K
  • Wave

    Wave

    717
  • Illos Knowledge Sources

    Illos Knowledge Sources

    54
  • Phosphor 30

    Phosphor 30

    314
  • animated pattern cloud

    animated pattern cloud

    634
  • Stripe like gradient-shader

    Stripe like gradient-shader

    272
  • Shader Background

    Shader Background

    2K