Three.js可视化企业实战WEBGL课|完结
获取ZY↑↑方打开链接↑↑
Three.js 常见几何体入门指南
Three.js 是一个基于 WebGL 的 JavaScript 库,用于创建和展示 3D 图形。它简化了 WebGL 的复杂性,使得开发者能够更容易地创建交互式的 3D 应用程序。本文将介绍 Three.js 中一些最常见的几何体类型及其基本用法。
一、几何体概述
在 Three.js 中,几何体(Geometry)是构成 3D 对象的基础。每个几何体都由顶点(vertices)、边(edges)和面(faces)组成。Three.js 提供了多种内置的几何体,可以用来创建各种形状。
二、常见几何体介绍
1. BoxGeometry(长方体)
BoxGeometry 用于创建一个长方体。可以通过指定宽度(width)、高度(height)和深度(depth)来创建一个长方体。
示例代码:
javascript浅色版本1const geometry = new THREE.BoxGeometry(1, 1, 1);2const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });3const cube = new THREE.Mesh(geometry, material);4scene.add(cube);
2. SphereGeometry(球体)
SphereGeometry 创建一个球体。可以通过指定半径(radius)、宽度分割数(widthSegments)和高度分割数(heightSegments)来控制球体的形状。
示例代码:
javascript浅色版本1const geometry = new THREE.SphereGeometry(1, 32, 32);2const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });3const sphere = new THREE.Mesh(geometry, material);4scene.add(sphere);
3. CylinderGeometry(圆柱体)
CylinderGeometry 创建一个圆柱体。可以指定顶部半径(radiusTop)、底部半径(radiusBottom)、高度(height)以及径向分割数(radialSegments)。
示例代码:
javascript浅色版本1const geometry = new THREE.CylinderGeometry(1, 1, 2, 32);2const material = new THREE.MeshBasicMaterial({ color: 0x0000ff });3const cylinder = new THREE.Mesh(geometry, material);4scene.add(cylinder);
4. ConeGeometry(圆锥体)
ConeGeometry 创建一个圆锥体。与圆柱体类似,但是顶部半径为零。
示例代码:
javascript浅色版本1const geometry = new THREE.ConeGeometry(1, 2, 32);2const material = new THREE.MeshLambertMaterial({ color: 0xffff00 });3const cone = new THREE.Mesh(geometry, material);4scene.add(cone);
5. TorusGeometry(环形)
TorusGeometry 创建一个环形。可以通过设置管的半径(radius)、管的半径(tube)、径向分割数(radialSegments)和管状分割数(tubularSegments)来创建环形。
示例代码:
javascript浅色版本1const geometry = new THREE.TorusGeometry(1, 0.2, 16, 100);2const material = new THREE.MeshPhongMaterial({ color: 0x00ffff });3const torus = new THREE.Mesh(geometry, material);4scene.add(torus);
6. PlaneGeometry(平面)
PlaneGeometry 创建一个矩形平面。可以指定宽度和高度。
示例代码:
javascript浅色版本1const geometry = new THREE.PlaneGeometry(10, 10);2const material = new THREE.MeshStandardMaterial({ color: 0x808080 });3const plane = new THREE.Mesh(geometry, material);4plane.rotation.x = -Math.PI / 2;5scene.add(plane);
三、材质与光照
除了几何体之外,Three.js 还提供了丰富的材质(Material)选项。上述示例中使用了 MeshBasicMaterial 和 MeshPhongMaterial,前者不支持光照,后者则可以模拟光照效果。为了使场景更加真实,通常还需要添加光源(Light)。
示例代码:
javascript浅色版本1const ambientLight = new THREE.AmbientLight(0xffffff); // 环境光2scene.add(ambientLight);34const directionalLight = new THREE.DirectionalLight(0xffffff, 1);5directionalLight.position.set(1, 1, 1).normalize();6scene.add(directionalLight);
四、总结
本文介绍了Three.js中的一些常用几何体及其基本使用方法。当然,Three.js 支持的几何体远不止这些,还包括更复杂的几何体如多边形网格、参数化几何体等。掌握这些基本概念之后,就可以开始探索更高级的功能了。希望本文对你学习Three.js有所帮助!