Wave Terrain · How it works & code
Vertex Animation Generates Terrain
Runtime logic
Visiting `/threejs/wave`, DemoHost lazy-loads `demos/wave.js` (registry `mod: 'wave'`) and calls `mountWave(host, { variant: 'wave' })`. `createThreeStage` sets up WebGLRenderer, Scene, PerspectiveCamera and OrbitControls, plus the info panel. The module registers its per-frame callback with `S.onFrame`. Every `requestAnimationFrame`: read controls, advance a speed-scaled clock (dt ≤ 50 ms), run the frame callback; returned readouts go to the info panel. Changing parameters: colour/speed/size apply live; structural ones remount; leaving the page cancels rAF, removes listeners and frees resources.
Environment
Canvas 2D: 2D canvas drawing; WebGL (three.js): WebGL through three.js WebGLRenderer; requestAnimationFrame: Display-synced animation loop; ResizeObserver: Canvas follows container size; Pointer Events: Unified mouse/touch/pen events; devicePixelRatio: Crisp HiDPI rendering (capped at 2×) · react 18.3.1, react-router-dom 6.30.6, vite 5.4.21, three 0.170.0
Dependencies
three 0.170.0, three/addons/controls/OrbitControls.js 0.170.0, react 18.3.1
Imported APIs
createThreeStage — Shared three.js stage: WebGLRenderer, scene, perspective camera, OrbitControls, auto framing and render loop; THREE — three.js namespace; fmt — Number formatting (fixed decimals); F — Formula block HTML; S.get — Reads current control values; S.onFrame — Registers a per-frame callback; its return value feeds the info panel; THREE.AmbientLight — Ambient light; THREE.DirectionalLight — Directional (sun) light; THREE.PlaneGeometry — Plane geometry; THREE.MeshStandardMaterial — PBR standard material; THREE.Mesh — Mesh (geometry + material)
Source code
frontend/src/demos/wave.js: wave.js (L1-L54)
Code walkthrough
L4-14: `PARAMS_SPEC` (constant/table). L15-15: `W0` (constant/table). L16-32: `DOC` (constant/table). L34-54: `mountWave` (function); creates three.js objects `AmbientLight`, `DirectionalLight`, `PlaneGeometry`, `MeshStandardMaterial`, `Mesh`; math via `Math.max`, `Math.min`, `Math.round`, `Math.sin`, `Math.cos`; returns readouts `A`, `k`, `lam`, `w`, `y0`, `verts` to the info panel.
Principles
y(x, z, t) = A·sin(k·x + ω·t) + A·cos(0.9k·z + 0.8ω·t) λ = 2π / k,T = 2π / ω A plane is cut N×N A small grid, the height of each grid (top point) y 每帧按正弦公式重新计算,于是整张网格像海面一样起伏,这叫 Top Animation 。 Two waves each x 和 z The direction spreads and overlaps, so the summit is staggered. Out“Diamond”Pattern. Amplitude A How high is the decision? Wave Number k It's decided how dense it is λ The shorter, ω How fast it's decided. Recalculate method lines when height is updated computeVertexNormals), It changes with the light.