1. Three.js Geometry核心概念与进阶方向
Three.js中的Geometry是构建3D世界的基础元素,它定义了物体的形状和结构。与初学者常用的基础几何体(如BoxGeometry、SphereGeometry)不同,进阶几何操作需要深入理解顶点、面和UV映射等底层概念。
现代Three.js项目通常采用BufferGeometry而非传统的Geometry类,因为前者内存效率更高。BufferGeometry使用类型化数组(Typed Arrays)存储顶点数据,这对性能敏感的应用至关重要。例如,一个包含10,000个三角形的模型,在BufferGeometry中只需要一个Float32Array来存储所有顶点坐标,而传统Geometry会产生大量独立对象。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 自定义几何体创建实战
2.1 使用ShapeGeometry创建复杂2D形状
ShapeGeometry特别适合需要从2D路径生成3D几何体的场景。以下是一个创建齿轮形状的完整示例:
javascript复制const gearShape = new THREE.Shape();
const radius = 5;
const teethSize = 1.5;
const teethCount = 12;
gearShape.moveTo(radius + teethSize, 0);
for (let i = 0; i < teethCount * 2; i++) {
const angle = (i / teethCount) * Math.PI;
const isOuter = i % 2 === 0;
const currentRadius = isOuter ? radius + teethSize : radius - teethSize;
gearShape.lineTo(
Math.cos(angle) * currentRadius,
Math.sin(angle) * currentRadius
);
}
gearShape.lineTo(radius + teethSize, 0);
const geometry = new THREE.ShapeGeometry(gearShape, {
curveSegments: 32 // 更高的分段数使曲线更平滑
});
关键参数说明:
curveSegments:控制曲线近似精度,值越大曲线越平滑但顶点数越多extrudePath:可选的3D路径,用于将2D形状沿路径拉伸成3D物体
2.2 动态几何体修改技巧
运行时修改几何体需要特别注意性能优化。最佳实践是:
- 获取顶点数组的引用
- 批量修改顶点数据
- 标记需要更新的属性
javascript复制const positionAttribute = geometry.attributes.position;
const positions = positionAttribute.array;
// 批量修改顶点(波浪效果示例)
for (let i = 0; i < positions.length; i += 3) {
const x = positions[i];
const z = positions[i + 2];
positions[i + 1] = Math.sin(x * 0.5 + Date.now(
