简单表述就是给正方形的六个面贴上不同的壁纸,而人位于正方体的中间,就会感觉到3DVR的效果,多个场景就构建多个立方体组合
创建一个div并设置宽高为整个屏幕,获取div的dom
<div style="width:100vw;height:100vh" ref="squareDom"></div>
创建一个场景
- const scene = new THREE.Scene()
初始化相机
- const camera = new THREE.PerspectiveCamera(75,window.innerWidth / window.innerHeight, 0.1, 1000)
设置相机的位置
初始化渲染器
1 2
| const render = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight)
|
初始化dom
- const squareDom = ref(null)
渲染函数渲染场景并请求动画帧和实时更新控制器
1 2 3 4 5
| const render = () => { controls && controls.update() renderer.render(scene, camera) requestAnimationFrame(render) }
|
添加轨道控制器并添加阻尼
1 2 3
| const controls = new OrbitControls(camera, squareDom.value) controls.enableDamping = true controls.dampingFactor = 0.05
|
创建立方体(非hdr图)
- const geometry = new THREE.BoxGeometry(10,10,10);
将六张图片加载进来
1 2 3 4 5 6
| let boxMaterials = [] const texture = new THREE.TextureLoader().load("") boxMaterials.push(new THREE.MeshBasicMaterial({ map: texture})) const cube = new THREE.Mesh(geometry,boxMaterials) cube.geometry.scale(1,1,-1) scene.add(cube)
|
如果有图片的位置角度对不上需要旋转,旋转后添加材料,否则直接添加材料
1 2
| texture.rotation = Math.PI texture.center = new THREE.Vector2(0.5, 0.5)
|
如果是hdr后缀的全景图是球体的映射
创建球体(hdr图)并添加全景图
1 2 3 4 5 6 7 8
| const geometry = new THREE.SphereGeometry(5,32,32); const rgbLoader = new RGBELoader() rgbLoader.load("", (texture) => { const material = new THREE.MeshBasicMaterial({ map: texture}) const sphere = new THREE.Mesh(geometry, material) sphere.geometry.scale(1,1,-1) scene.add(sphere) })
|
以下内容在onMounted生命周期函数中写的
挂载完毕后获取dom
- squareDom.value.appendChild(renderer.domElement)
调用渲染函数