在three.js中有一种几何体叫BufferGeometry,也就是缓冲几何体对象,其核心就是使用顶点数据来绘制几何体

1.代码

let arr1 = []
let arr2 = []
// 1.第一步
for (let i = 0; i < 10 * 3; i++) {
const x = Math.round(Math.random() * 50)
const y = Math.round(Math.random() * 50)
const z = Math.round(Math.random() * 50)
// 一个顶点的位置数据
arr1.push(x)
arr1.push(y)
arr1.push(z)
// 一个顶点的颜色 数据
// Separate RGB values between 0 and 1
arr2.push(Math.random())
arr2.push(Math.random())
arr2.push(Math.random())
}
// 2.第二步:将数组转换成类型化数组
const vertices = new Float32Array(arr1)
const colors = new Float32Array(arr2)
// 3.第三步
const geometry = new THREE.BufferGeometry() // 声明一个缓冲几何体对象
const pos = new THREE.BufferAttribute(vertices, 3)
const col = new THREE.BufferAttribute(colors, 3)
geometry.attributes.position = pos
geometry.attributes.color = col
const mat = new THREE.LineBasicMaterial({
vertexColors: true,
side: THREE.DoubleSide, //两面可见
})
const line = new THREE.Line(geometry, mat)
scene.add(line)

2.效果

#yyds干货盘点#three.js中使用BufferGeometry绘制三维物体_3D

也可以绘制点和面,需要修改材质和网格对象

// 点
const mat = new THREE.PointsMaterial({
vertexColors: true,
size: 10
})
const line = new THREE.Points(geometry, mat)
scene.add(line)

// 面 -> 网格对象
const mat = new THREE.MeshBasicMaterial({
vertexColors: true,
side: THREE.DoubelSide
})
const line = new THREE.Mesh(geometry, mat)
scene.add(line)

#yyds干货盘点#three.js中使用BufferGeometry绘制三维物体_three.js_02

#yyds干货盘点#three.js中使用BufferGeometry绘制三维物体_3D_03

3.核心代码说明

#yyds干货盘点#three.js中使用BufferGeometry绘制三维物体_three.js_04

4.总结

  • BufferGeometry的使用
  • 颜色的构造函数的使用
  • 3个顶点数据绘制一个面