Atlaslog
Atlaslog / Examples / three.js / Materials Displacement
three.js · Runnable Example

Materials Displacement

Runnable three.js example: Materials Displacement. 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-materials-displacement.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/three-materials-displacement.html
<!--
  说明:置换贴图让平坦网格在着色阶段被抬起,几何体分段决定起伏能否看清
  核心逻辑:MeshStandardMaterial 的 displacementMap 采样 R 通道,再乘 displacementScale
  依赖: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:#0b1015}
  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="scv">4.0</b></span>
  <label>displacementScale <input type="range" id="sc" min="0" max="12" step="0.5" value="4"></label>
  <button id="wire">线框</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(0x0b1015);
scene.fog = new THREE.Fog(0x0b1015, 42, 86);

const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 300);
camera.position.set(22, 16, 26);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 2, 0);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.49;
controls.minDistance = 8;
controls.maxDistance = 80;
controls.update();

scene.add(new THREE.HemisphereLight(0xb4d0ec, 0x121a18, 1.2));
const sun = new THREE.DirectionalLight(0xfff0d6, 2.4);
sun.position.set(-16, 24, 12);
scene.add(sun);

/* 置换贴图:多层正弦叠加,得到连续起伏 */
const SIZE = 256;
const dispCanvas = document.createElement('canvas');
dispCanvas.width = dispCanvas.height = SIZE;
const dctx = dispCanvas.getContext('2d');
const img = dctx.createImageData(SIZE, SIZE);

for (let y = 0; y < SIZE; y++) {
  for (let x = 0; x < SIZE; x++) {
    const u = x / SIZE;
    const v = y / SIZE;
    let h = 0.5
      + 0.26 * Math.sin(u * Math.PI * 5.2) * Math.cos(v * Math.PI * 4.1)
      + 0.15 * Math.sin(u * Math.PI * 11.0 + v * Math.PI * 7.0)
      + 0.09 * Math.cos(u * Math.PI * 19.0 - v * Math.PI * 13.0);

    /* 中央一个高斯峰,让画面有明确的主峰 */
    const dx = u - 0.46;
    const dy = v - 0.42;
    h += 0.5 * Math.exp(-(dx * dx + dy * dy) * 30);
    h = Math.max(0, Math.min(1, h));

    const i = (y * SIZE + x) * 4;
    const k = Math.round(h * 255);
    img.data[i] = k;
    img.data[i + 1] = k;
    img.data[i + 2] = k;
    img.data[i + 3] = 255;
  }
}
dctx.putImageData(img, 0, 0);

const dispTex = new THREE.CanvasTexture(dispCanvas);
dispTex.wrapS = dispTex.wrapT = THREE.ClampToEdgeWrapping;

/* 颜色贴图:等高线风格的横向条纹,随高度变亮 */
const colorCanvas = document.createElement('canvas');
colorCanvas.width = colorCanvas.height = SIZE;
const cctx = colorCanvas.getContext('2d');
const img2 = cctx.createImageData(SIZE, SIZE);

for (let y = 0; y < SIZE; y++) {
  for (let x = 0; x < SIZE; x++) {
    const h = img.data[(y * SIZE + x) * 4] / 255;
    const band = Math.abs(Math.sin(h * Math.PI * 9)) < 0.12 ? 0.72 : 1;
    const r = Math.round((40 + h * 175) * band);
    const g = Math.round((70 + h * 150) * band);
    const b = Math.round((95 + h * 120) * band);
    const i = (y * SIZE + x) * 4;
    img2.data[i] = r;
    img2.data[i + 1] = g;
    img2.data[i + 2] = b;
    img2.data[i + 3] = 255;
  }
}
cctx.putImageData(img2, 0, 0);

const colorTex = new THREE.CanvasTexture(colorCanvas);
colorTex.colorSpace = THREE.SRGBColorSpace;
colorTex.wrapS = colorTex.wrapT = THREE.ClampToEdgeWrapping;

const geo = new THREE.PlaneGeometry(44, 44, 260, 260);
geo.rotateX(-Math.PI / 2);

const mat = new THREE.MeshStandardMaterial({
  map: colorTex,
  displacementMap: dispTex,
  displacementScale: 4,
  displacementBias: 0,
  roughness: 0.86,
  metalness: 0.04
});

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

/* 底座:遮住网格边缘,斜视时不会看到悬空的平面 */
const base = new THREE.Mesh(
  new THREE.BoxGeometry(44, 6, 44),
  new THREE.MeshStandardMaterial({ color: 0x111820, roughness: 1 })
);
base.position.y = -3;
scene.add(base);

const scEl = document.getElementById('sc');
const scvEl = document.getElementById('scv');
scEl.addEventListener('input', function () {
  const v = Number(scEl.value);
  mat.displacementScale = v;
  scvEl.textContent = v.toFixed(1);
});

let wire = false;
const wireBtn = document.getElementById('wire');
wireBtn.addEventListener('click', function () {
  wire = !wire;
  mat.wireframe = wire;
  wireBtn.textContent = wire ? '实体' : '线框';
});

renderer.setAnimationLoop(function () {
  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 · EXAMPLEMath Obb three.js · EXAMPLEModel Rotate three.js · EXAMPLEMulti Camera