效果展示
需求:做一个3D模型展示,需要灯光、底座、模型旋转、阴影等,先看效果
ps:项目架构 vue3+ts,其他架构的改方法就行
Video_2024-05-10_165926
整体代码展示
1,创建场景,渲染器,相机,这步不在赘述
2,创建地板及地板材质
const geometry = new THREE.CircleGeometry(200, 200)
const material = new THREE.MeshLambertMaterial({ color: 0xffffff })
material.lightMapIntensity = 0
const base = new THREE.Mesh(geometry, material)
base.castShadow = true
base.receiveShadow = true
base.rotation.x = (Math.PI * 3) / 2
scene.add(base)
2,添加灯光
// 环境灯光
const hemiLight = new THREE.HemisphereLight(0xffffff, 0x8d8d8d, 1.8)
scene.add(hemiLight)
//倾斜聚光灯
spotLight = new THREE.SpotLight(0xffffff, 1000)
spotLight.intensity = 5
spotLight.position.set(0, 250, 200)
spotLight.angle = Math.PI / 12
spotLight.penumbra = 0.9
spotLight.decay = 0.5
spotLight.distance = 0
spotLight.castShadow = true
spotLight.shadow.mapSize.width = 1024
spotLight.shadow.mapSize.height = 1024
//顶端聚光灯
spotLight2 = new THREE.SpotLight(0xffffff, 100)
spotLight2.intensity = 7
spotLight2.position.set(0, 150, 0)
spotLight2.angle = Math.PI / 4
spotLight2.penumbra = 0.3
spotLight2.decay = 0.5
spotLight2.distance = 0
spotLight2.shadow.mapSize.width = 1024
spotLight2.shadow.mapSize.height = 1024
spotLight2.shadow.focus = 1
scene.add(spotLight)
scene.add(spotLight2)
3,加载模型
const modelUrl = '../assets/old_building_3d_scan_1k.glb'//模型路径
LoadModel(modelUrl)
const LoadModel = async (url: string) => {
const loader = new GLTFLoader()
loader.load(new URL(url, import.meta.url).href, function (gltf: any) {
gltf.scene.position.set(0, 0, 0)//设置位置
gltf.scene.traverse((obj: any) => {
obj.castShadow = true //开启阴影
if (obj.isMesh) {
// 调整金属度
obj.material.metalness = -3
}
})
gltf.scene.scale.set(3, 3, 3)//放大3倍
scene.add(gltf.scene)
})
}
4,想要旋转和阻尼效果,可以在controls中直接开
controls.value = new OrbitControls(camera.value, renderer.value.domElement) //MapControls:自由视角
controls.value.enableDamping = true // 启用阻尼效果,使旋转更加平滑
controls.value.dampingFactor = 0.05 // 阻尼系数
controls.value.autoRotate = true // 自动旋转
autoRotate.value = true
controls.value.autoRotateSpeed = 10.0 // 自动旋转速度
后语
以上3D展示效果原理实质是相机转动达到环绕展示效果,比较简单,后面接了一个需求是让相机视角固定,鼠标拖动让模型旋转,并添加固定的背景logo,这个就稍稍复杂点,先展示做的效果吧
Video_2024-05-10_173655
因为这个较为复杂,这种需求也较少,所以这里就不展示源码了,需要的朋友可以单独找我要