Three.js 实现3D汽车展示与颜色定制功能分析
1. 项目概述
这是一个基于 Vue 3 和 Three.js 实现的 3D 汽车展示项目,主要功能包括:
- 3D 汽车模型展示
- 实时颜色切换功能
- 支持模型旋转查看
- 材质效果定制
2. 效果
3. 核心功能实现分析
3.1 场景初始化
const initThree = async () => {
// 创建场景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x787878)
// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 2, 3)
// 创建渲染器
const renderer = new THREE.WebGLRenderer({
antialias: true,
})
}
场景初始化包含了:
- 设置灰色背景
- 配置透视相机
- 创建支持抗锯齿的渲染器
3.2 材质设置
项目使用了 MeshPhysicalMaterial
来创建金属材质效果:
const metalMaterial = new THREE.MeshPhysicalMaterial({
color: '#5cb4c0',
metalness: 1,
roughness: 0.5,
clearcoat: 1,
clearcoatRoughness: 0,
})
材质特性:
- metalness: 控制金属感
- roughness: 控制粗糙度
- clearcoat: 清漆效果
- clearcoatRoughness: 清漆粗糙度
3.3 灯光设置
项目使用了多个平行光来创建完整的光照效果:
const light1 = new THREE.DirectionalLight(0xffffff, 1);
light1.position.set(0, 0, 10);
scene.add(light1);
// ... 共设置了7个不同位置的平行光
灯光布局:
- 从不同角度照射模型
- 确保模型各个部分都能得到充分照明
- 增强金属材质的视觉效果
3.4 模型加载
项目支持两种格式的模型加载:
const loadFBXModel = (url) => {
return new Promise((resolve, reject) => {
const loader = new FBXLoader();
loader.load(url,
(object) => resolve(object),
undefined,
(error) => reject(error)
);
});
}
const loadGLTFModel = (url) => {
return new Promise((resolve, reject) => {
const loader = new GLTFLoader();
loader.load(url,
(object) => resolve(object.scene),
undefined,
(error) => reject(error)
);
});
}
特点:
- 封装为 Promise 形式
- 支持 FBX 和 GLTF 两种格式
- 统一的错误处理
3.5 颜色切换功能
const setColor = (index) => {
selectIndex.value = index
changeGroupColor(carBody.value, colors.value[index])
}
const changeGroupColor = (group, color) => {
group.traverse(function (object) {
if (object.isMesh) {
object.material.color.set(color)
}
});
}
实现特点:
- 支持多个预设颜色
- 递归遍历模型所有网格
- 实时更新材质颜色
3.6 UI 交互设计
<div class="meun">
<h1>汽车颜色选配</h1>
<div class="color-options">
<div :class="index==selectIndex?'active':''"
v-for="(item,index) in colors"
:key="item"
:style="{ backgroundColor: item }"
@click="setColor(index)">
</div>
</div>
</div>
交互特点:
- 简洁的颜色选择界面
- 当前选中颜色高亮显示
- 半透明背景增加层次感
4. 实用工具函数
4.1 模型尺寸调整
const setModelSize = (model, targetSize) => {
const box = new THREE.Box3().setFromObject(model);
const size = box.getSize(new THREE.Vector3());
const scale = targetSize / Math.max(size.x, size.y, size.z);
model.scale.set(scale, scale, scale);
}
功能:
- 计算模型包围盒
- 基于目标尺寸计算缩放比例
- 统一缩放三个轴向
5. 性能优化考虑
-
渲染优化:
- 开启抗锯齿
- 使用 requestAnimationFrame 实现渲染循环
-
模型优化:
- 统一的材质管理
- 按需加载模型
- 适当的模型缩放
6. 可改进空间
- 性能优化:
- 添加模型加载进度提示
- 实现模型细节层级(LOD)
- 功能扩展:
- 添加材质参数调节界面
- 支持更多自定义颜色
- 添加车辆配置保存功能
总结
这个项目展示了 Three.js 在 Web 3D 展示中的应用,通过合理的架构设计和模块划分,实现了一个功能完整的汽车展示与定制系统。项目中的许多设计模式和工具函数都具有较好的复用价值,可以作为类似项目的参考。