0%

17 山脉地形高度可视化 - Threejs入门

利用混合颜色,绘制一个渐变的地形。 [ 练一练 ] [ 看一看 ]

加载一个GLTF格式的地形模型,并根据模型的高度数据(y坐标)为每个顶点分配颜色。颜色从蓝色(最低点)渐变到红色(最高点),并应用于模型的材质。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
0.1,
100
)
camera.position.set(20, 5, 0)

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
app.appendChild(renderer.domElement)

// 创建环境光
const ambLight = new THREE.AmbientLight()
// 创建平行光
const dirLight = new THREE.DirectionalLight()
// 设置平行光位置
dirLight.position.set(5, 5, 5)
// 添加到场景中
scene.add(ambLight, dirLight)

// 利用混合颜色,绘制一个渐变的地形
const loader = new GLTFLoader()
loader.load('./models/地形.glb', (glb) => {
glb.scene.scale.set(3, 3, 3)
const mesh = glb.scene.children[0]
const pos = mesh.geometry.attributes.position
const count = pos.count

const yArr = []
for (let i = 0; i < count; i++) {
yArr.push(pos.getY(i))
}

yArr.sort((a, b) => a - b)

const minY = yArr[0]
const maxY = yArr[yArr.length - 1]
const yHeight = maxY - minY

const colorArr = []
const c1 = new THREE.Color(0x0000ff)
const c2 = new THREE.Color(0xff0000)

for (let i = 0; i < count; i++) {
const percent = (pos.getY(i) - minY) / yHeight

const c = c1.clone().lerp(c2, percent)
colorArr.push(c.r, c.g, c.b)
}

const colors = new Float32Array(colorArr)

mesh.geometry.attributes.color = new THREE.BufferAttribute(colors, 3)

mesh.material = new THREE.MeshLambertMaterial({
vertexColors: true,
side: THREE.DoubleSide,
})

scene.add(glb.scene)
})

const controls = new OrbitControls(camera, app)

renderer.setAnimationLoop(() => {
renderer.render(scene, camera)
})

演示效果