0%

06 自由发挥 - 空白几何体 - Threejs入门

缓冲类型几何体(BufferGeometry),允许开发者自由地定义其形状和结构。通过精心设计顶点数据,你可以在这片空白的画布上绘制出任何所需的几何形状,从而创造出丰富多彩的三维模型。 [ 练一练 ] [ 看一看 ]

点模型 Points 有自己的点材质 PointsMaterial。
线模型 Line 有自己的线材质 LineBasicMaterial 和 LineDashedMaterial。

示例代码

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'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

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

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
0.1,
1000
)
camera.position.set(0, 0, 60)

const renderer = new THREE.WebGLRenderer({
antialias: true,
})
renderer.setSize(window.innerWidth, window.innerHeight)
$app.appendChild(renderer.domElement)

// 定义一个空的几何体对象
const emptyGeometry = new THREE.BufferGeometry()

// 创建顶点数据,用类型化数组存储, 0, 0, 0, 5, 0, 0, 0, 5, 0
const vertices = new Float32Array([
0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 10, 0
])

// 创建位置属性缓冲区对象,三个为一组,表示xyz对象
const positionAttr = new THREE.BufferAttribute(vertices, 3)

// 设置几何体的顶点位置属性
emptyGeometry.attributes.position = positionAttr

// 定义一个点模型材质
const pointMtr = new THREE.PointsMaterial()

// 创建一个点模型对象,并添加到场景中
const pointsObj = new THREE.Points(emptyGeometry, pointMtr)
scene.add(pointsObj)

// 定义一个线材质
const lineMaterial = new THREE.LineBasicMaterial()

// 定义一个线模型对象
// 连续的线
// const lineObj = new THREE.Line(emptyGeometry, lineMaterial)
// 头尾相接线
// const lineObj = new THREE.LineLoop(emptyGeometry, lineMaterial)
// 非连续的线段
const lineObj = new THREE.LineSegments(emptyGeometry, lineMaterial)
lineObj.position.set(-2, -2, 0)

// 定义一个网格材质
const meshMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide
})
// 定义一个网格对象
const meshObj = new THREE.Mesh(emptyGeometry, meshMaterial)
meshObj.position.set(2, 2, 0)

scene.add(lineObj, meshObj)

new OrbitControls(camera, renderer.domElement)

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

演示效果