Atlaslog
Atlaslog / Examples / three.js / Water
three.js · Runnable Example

Water

Runnable three.js example: Water. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All three.js examples
/demos/three-water.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/three-water.html
<!--
  说明:水面由顶点位移与菲涅尔混合构成,没有任何贴图,波纹全部在着色器里算
  核心逻辑:顶点按两组正弦波抬升,片元按视角夹角混合深浅水色并叠加高光
  依赖:three.js 0.160.0、OrbitControls · jsDelivr CDN(ESM + importmap)
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>水面着色</title>
<style>
  html,body{height:100%;margin:0;background:#07121b}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#e6e8ec}
  .bar{flex:0 0 auto;padding:8px 12px;background:#161b22;border-bottom:1px solid #252c36;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600;font-variant-numeric:tabular-nums}
  .bar input[type=range]{width:120px;accent-color:#4f9ef8}
  .bar button{font:inherit;font-size:12px;padding:4px 10px;border-radius:5px;cursor:pointer;
       border:1px solid #303845;background:#1d2531;color:#c8d2e0}
  .bar button:hover{background:#253040}
  .bar .sp{flex:1 1 auto}
  #stage{flex:1 1 auto;min-height:0;position:relative}
  #stage canvas{display:block}
</style>
</head>
<body>
<div class="bar">
  <span>浪高 <b id="hv">0.6</b></span>
  <label>浪高 <input type="range" id="h" min="0.1" max="1.6" step="0.1" value="0.6"></label>
  <span>流速 <b id="sv">1.0</b></span>
  <label>流速 <input type="range" id="s" min="0.2" max="2.4" step="0.1" value="1"></label>
  <button id="pause">暂停</button>
  <span class="sp"></span>
  <span>拖拽旋转 · 滚轮缩放</span>
</div>
<div id="stage"></div>

<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
  }
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const stage = document.getElementById('stage');
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(stage.clientWidth, stage.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
stage.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07121b);

const camera = new THREE.PerspectiveCamera(50, stage.clientWidth / stage.clientHeight, 0.1, 400);
camera.position.set(16, 8, 20);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.48;
controls.minDistance = 6;
controls.maxDistance = 60;
controls.update();

scene.add(new THREE.HemisphereLight(0x9ec8e8, 0x081018, 1.0));

/* 远处的地平线与天空渐变,用一个大平面代替 */
const horizon = new THREE.Mesh(
  new THREE.SphereGeometry(160, 32, 16, 0, Math.PI * 2, 0, Math.PI / 2),
  new THREE.MeshBasicMaterial({
    color: 0x14304a,
    side: THREE.BackSide
  })
);
scene.add(horizon);

/* 水面:足够细分的网格才能让顶点波看起来平滑 */
const geo = new THREE.PlaneGeometry(120, 120, 220, 220);
geo.rotateX(-Math.PI / 2);

const uniforms = {
  uTime: { value: 0 },
  uAmp: { value: 0.6 },
  uSpeed: { value: 1.0 },
  uDeep: { value: new THREE.Color(0x0a2233) },
  uShallow: { value: new THREE.Color(0x2f7f8f) },
  uSky: { value: new THREE.Color(0x9fc4dd) },
  uSun: { value: new THREE.Vector3(-0.4, 0.55, 0.35).normalize() }
};

const mat = new THREE.ShaderMaterial({
  uniforms: uniforms,
  vertexShader: `
    uniform float uTime;
    uniform float uAmp;
    uniform float uSpeed;
    varying vec3 vWorld;
    varying float vWave;

    void main() {
      vec3 p = position;
      /* 三组不同方向与频率的波叠加,避免出现明显的重复条纹 */
      float t = uTime * uSpeed;
      float w1 = sin(p.x * 0.22 + t * 1.1) * cos(p.z * 0.18 - t * 0.8);
      float w2 = sin((p.x + p.z) * 0.42 - t * 1.7);
      float w3 = cos(p.z * 0.65 + t * 1.3) * 0.5;
      float h = (w1 + w2 * 0.45 + w3 * 0.3) * uAmp;

      p.y += h;
      vWave = h;

      vec4 world = modelMatrix * vec4(p, 1.0);
      vWorld = world.xyz;
      gl_Position = projectionMatrix * viewMatrix * world;
    }
  `,
  fragmentShader: `
    uniform vec3 uDeep;
    uniform vec3 uShallow;
    uniform vec3 uSky;
    uniform vec3 uSun;
    uniform float uTime;
    varying vec3 vWorld;
    varying float vWave;

    void main() {
      vec3 viewDir = normalize(cameraPosition - vWorld);

      /* 用波的导数近似法线,省掉额外的法线计算 */
      float dx = cos(vWorld.x * 0.22 + uTime) * 0.22;
      float dz = cos(vWorld.z * 0.65 + uTime * 1.3) * 0.2;
      vec3 n = normalize(vec3(-dx * 0.9, 1.0, -dz * 0.9));

      float fres = pow(1.0 - max(dot(viewDir, n), 0.0), 3.0);

      /* 波峰偏浅、波谷偏深 */
      float t = clamp(vWave * 0.9 + 0.5, 0.0, 1.0);
      vec3 water = mix(uDeep, uShallow, t);

      /* 天空反射 + 太阳高光 */
      vec3 refl = mix(water, uSky, fres * 0.85);
      vec3 h = normalize(uSun + viewDir);
      float spec = pow(max(dot(n, h), 0.0), 120.0);

      gl_FragColor = vec4(refl + vec3(1.0, 0.95, 0.85) * spec * 0.9, 1.0);
    }
  `
});

const water = new THREE.Mesh(geo, mat);
scene.add(water);

/* 几个浮标:随波起伏,用来确认水面确实在动 */
const buoyMat = new THREE.MeshStandardMaterial({ color: 0xffb347, roughness: 0.4, metalness: 0.3 });
const buoys = [];
for (let i = 0; i < 7; i++) {
  const b = new THREE.Mesh(new THREE.CylinderGeometry(0.28, 0.36, 1.1, 12), buoyMat);
  b.userData.phase = i * 0.9;
  b.userData.r = 3 + i * 2.2;
  scene.add(b);
  buoys.push(b);
}

const hEl = document.getElementById('h');
const hvEl = document.getElementById('hv');
hEl.addEventListener('input', function () {
  const v = Number(hEl.value);
  uniforms.uAmp.value = v;
  hvEl.textContent = v.toFixed(1);
});

const sEl = document.getElementById('s');
const svEl = document.getElementById('sv');
sEl.addEventListener('input', function () {
  const v = Number(sEl.value);
  uniforms.uSpeed.value = v;
  svEl.textContent = v.toFixed(1);
});

let playing = true;
const pauseBtn = document.getElementById('pause');
pauseBtn.addEventListener('click', function () {
  playing = !playing;
  pauseBtn.textContent = playing ? '暂停' : '继续';
});

const clock = new THREE.Clock();
let t = 0;

renderer.setAnimationLoop(function () {
  const dt = Math.min(clock.getDelta(), 0.1);
  if (playing) t += dt;
  uniforms.uTime.value = t;

  const amp = uniforms.uAmp.value;
  const sp = uniforms.uSpeed.value;
  buoys.forEach(function (b) {
    const a = b.userData.phase;
    const r = b.userData.r;
    const x = Math.cos(a) * r;
    const z = Math.sin(a) * r;
    const w1 = Math.sin(x * 0.22 + t * sp * 1.1) * Math.cos(z * 0.18 - t * sp * 0.8);
    const w2 = Math.sin((x + z) * 0.42 - t * sp * 1.7);
    const w3 = Math.cos(z * 0.65 + t * sp * 1.3) * 0.5;
    b.position.set(x, (w1 + w2 * 0.45 + w3 * 0.3) * amp + 0.5, z);
    b.rotation.z = Math.sin(t * 1.4 + a) * 0.18;
    b.rotation.x = Math.cos(t * 1.1 + a) * 0.14;
  });

  controls.update();
  renderer.render(scene, camera);
});

window.addEventListener('resize', function () {
  const w = stage.clientWidth;
  const h = stage.clientHeight;
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);
});
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More three.js examples

three.js · EXAMPLEAnimation Blend three.js · EXAMPLEAxes three.js · EXAMPLEBuffer Lines