0%

05 GUI可视化调整三维场景 - Threejs入门

通过GUI库,可以对三维场景参数动态调整,方便调试。 [ 练一练 ] [ 看一看 ]

示例代码

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
import * as THREE from 'three'

// 引入GUI
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js'

const $app = document.getElementById('app')

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
1,
1000
)
camera.position.z = 10

const renderer = new THREE.WebGLRenderer({
antialias: true,
})

renderer.setSize(window.innerWidth, window.innerHeight)
$app.appendChild(renderer.domElement)

const boxGeo = new THREE.BoxGeometry(1, 1, 1)
const boxMtr = new THREE.MeshBasicMaterial()
const boxMesh = new THREE.Mesh(boxGeo, boxMtr)
scene.add(boxMesh)

// 实例化gui
const gui = new GUI()

// 动态修改模型颜色 (颜色选择器 形式)
gui
.addColor({ color: '#fff' }, 'color')
.name('颜色')
.onChange((value) => {
boxMesh.material.color.set(value)
})

// 动态控制模型显示隐藏 (勾选框 样式)
gui
.add({ show: true }, 'show')
.name('显示隐藏')
.onChange((value) => {
boxMesh.material.visible = value
})

// 创建一个分组
const twoGui = gui.addFolder('位置大小')

// 修改 boxMesh x位置, 设置一个友好的名字和精细度
twoGui.add(boxMesh.position, 'x', -2, 2).name('X轴').step(0.01)

// 动态控制模型大小 (下拉框 样式)
twoGui
.add({ scale: 1 }, 'scale', {
大: 2,
默认: 1,
小: 0.5,
})
.name('缩放')
.onChange((value) => {
boxMesh.scale.set(value, value, value)
})

function animation() {
renderer.render(scene, camera)
requestAnimationFrame(animation)
}

animation()

演示效果