Geometry Colors
Runnable three.js example: Geometry Colors. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
说明:同一份地形网格,用逐顶点颜色做分层设色,可在平滑渐变与分带两种模式间切换
核心逻辑:写入 color 属性后改 vertexColors,颜色随海拔按色带重新计算
依赖: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:#0d1117}
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}
.bar input[type=range]{width:130px;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 button.on{background:#1f3a5c;border-color:#2f5c8f;color:#cfe4ff}
.bar .sp{flex:1 1 auto}
#stage{flex:1 1 auto;min-height:0;position:relative}
#stage canvas{display:block}
#legend{position:absolute;right:12px;bottom:12px;width:14px;height:150px;border-radius:4px;
border:1px solid #2a3644}
</style>
</head>
<body>
<div class="bar">
<span>色带 <b>6</b> 级</span>
<label>级数 <input type="range" id="bands" min="3" max="12" step="1" value="6"></label>
<button id="mode" class="on">分层设色</button>
<span class="sp"></span>
<span>拖拽旋转 · 滚轮缩放</span>
</div>
<div id="stage"><canvas id="legend"></canvas></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(0x0d1117);
scene.fog = new THREE.Fog(0x0d1117, 36, 72);
const camera = new THREE.PerspectiveCamera(45, stage.clientWidth / stage.clientHeight, 0.1, 300);
camera.position.set(18, 16, 24);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 2.4, 0);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.49;
controls.minDistance = 8;
controls.maxDistance = 60;
controls.update();
scene.add(new THREE.HemisphereLight(0xbcd8ff, 0x121a16, 1.2));
const sun = new THREE.DirectionalLight(0xfff0d8, 2.3);
sun.position.set(-14, 22, 10);
scene.add(sun);
const SIZE = 32;
const SEG = 128;
function heightAt(x, z) {
const a = 1.4 * Math.sin(x * 0.32) * Math.cos(z * 0.28);
const b = 0.8 * Math.sin(x * 0.8 + z * 0.55);
const c = 4.2 * Math.exp(-((x - 3) * (x - 3) + (z + 3) * (z + 3)) / 30);
const d = -1.8 * Math.exp(-((x + 5) * (x + 5) + (z - 4) * (z - 4)) / 40);
return a + b + c + d;
}
const geo = new THREE.PlaneGeometry(SIZE, SIZE, SEG, SEG);
geo.rotateX(-Math.PI / 2);
const pos = geo.attributes.position;
const heights = new Float32Array(pos.count);
let minH = Infinity;
let maxH = -Infinity;
for (let i = 0; i < pos.count; i++) {
const h = heightAt(pos.getX(i), pos.getZ(i));
pos.setY(i, h);
heights[i] = h;
minH = Math.min(minH, h);
maxH = Math.max(maxH, h);
}
geo.computeVertexNormals();
/* 一套九段色带:深水、浅水、滩、草、林、灌、岩、雪 */
const RAMP = [
'#12324f', '#16557a', '#2f8ea6', '#8fbf8a',
'#d8d08a', '#c49a5e', '#9a7a58', '#b9b6b0', '#f4f6f8'
];
function rampColor(t) {
const s = THREE.MathUtils.clamp(t, 0, 1) * (RAMP.length - 1);
const i = Math.floor(s);
const f = s - i;
const c1 = new THREE.Color(RAMP[i]);
const c2 = new THREE.Color(RAMP[Math.min(i + 1, RAMP.length - 1)]);
return c1.clone().lerp(c2, f);
}
let banded = true;
let bandCount = 6;
function paint() {
const colors = new Float32Array(pos.count * 3);
const c = new THREE.Color();
for (let i = 0; i < pos.count; i++) {
let t = (heights[i] - minH) / (maxH - minH);
if (banded) {
const q = Math.min(bandCount - 1, Math.floor(t * bandCount));
t = q / (bandCount - 1);
}
c.copy(rampColor(THREE.MathUtils.clamp(t, 0, 1)));
colors[i * 3] = c.r;
colors[i * 3 + 1] = c.g;
colors[i * 3 + 2] = c.b;
}
geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
drawLegend();
}
const mat = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.92,
metalness: 0.03,
flatShading: false
});
const terrain = new THREE.Mesh(geo, mat);
scene.add(terrain);
const base = new THREE.Mesh(
new THREE.BoxGeometry(SIZE, 1.4, SIZE),
new THREE.MeshStandardMaterial({ color: 0x111922, roughness: 1 })
);
base.position.y = minH - 0.7;
scene.add(base);
/* 右下角图例:直接用 canvas 画渐变或色阶 */
const legend = document.getElementById('legend');
function drawLegend() {
const ctx = legend.getContext('2d');
const w = legend.width = 14;
const h = legend.height = 150;
const g = ctx.createLinearGradient(0, h, 0, 0);
if (banded) {
const n = bandCount;
const bh = h / n;
for (let i = 0; i < n; i++) {
ctx.fillStyle = rampColor(i / (n - 1)).getStyle();
ctx.fillRect(0, h - (i + 1) * bh, w, bh);
}
return;
}
for (let i = 0; i <= 16; i++) {
g.addColorStop(i / 16, rampColor(i / 16).getStyle());
}
ctx.fillStyle = g;
ctx.fillRect(0, 0, w, h);
}
const bandsEl = document.getElementById('bands');
bandsEl.addEventListener('input', function () {
bandCount = Number(bandsEl.value);
paint();
});
const modeBtn = document.getElementById('mode');
modeBtn.addEventListener('click', function () {
banded = !banded;
modeBtn.textContent = banded ? '分层设色' : '平滑渐变';
modeBtn.classList.toggle('on', banded);
paint();
});
paint();
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.