返回
用 three.js 构建几何图形:点、线与面的艺术
前端
2023-12-29 21:13:33
three.js 初探 (四):创造点、线与面
点、线和面构成了三维世界中物体形状的基础。three.js 为创建和操纵这些基本几何图形提供了强大的工具,这使得我们在虚拟世界中创造栩栩如生的对象成为可能。
点的魅力
点代表了三维空间中的离散位置。在 three.js 中,我们可以使用 PointsMaterial
和 Points
对象来创建点云。如下代码:
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array([0, 0, 0, 1, 1, 1, 1, 0, 0]);
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({color: 0xff0000, size: 0.1});
const points = new THREE.Points(geometry, material);
这将创建一个红色的点云,其中每个点的大小为 0.1。
线条的流动
线连接两个或多个点,勾勒出对象的轮廓。three.js 提供了 LineBasicMaterial
和 Line
对象来创建线条。代码如下:
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array([0, 0, 0, 1, 1, 1]);
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const material = new THREE.LineBasicMaterial({color: 0x00ff00});
const line = new THREE.Line(geometry, material);
这将创建一个从 (0, 0, 0) 到 (1, 1, 1) 的绿色线条。
面片的构成
面由三个或更多个点组成,形成多边形。three.js 使用 MeshBasicMaterial
和 Mesh
对象创建面片。例如:
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const material = new THREE.MeshBasicMaterial({color: 0x0000ff});
const mesh = new THREE.Mesh(geometry, material);
这将创建一个蓝色的三角形。
通过组合点、线和面,我们可以构建三维世界中的复杂对象。three.js 为我们提供了丰富的工具来塑造和操纵这些几何图形,使我们的创作充满活力和想象力。