js实现360全景
使用Three.js实现360全景
Three.js是一个基于WebGL的JavaScript库,可以轻松创建3D场景。以下是一个基本实现:

// 初始化场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建球体并添加纹理
const geometry = new THREE.SphereGeometry(500, 60, 40);
geometry.scale(-1, 1, 1); // 反转球体使其纹理在内部可见
const material = new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load('panorama.jpg')
});
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
// 设置相机位置
camera.position.set(0, 0, 0.1);
// 添加鼠标控制
let isUserInteracting = false,
lon = 0, lat = 0,
phi = 0, theta = 0;
document.addEventListener('mousedown', () => {
isUserInteracting = true;
});
document.addEventListener('mouseup', () => {
isUserInteracting = false;
});
document.addEventListener('mousemove', (e) => {
if (isUserInteracting) {
lon = (e.clientX - window.innerWidth / 2) * 0.1;
lat = (e.clientY - window.innerHeight / 2) * 0.1;
}
});
// 动画循环
function animate() {
requestAnimationFrame(animate);
if (!isUserInteracting) {
lon += 0.1;
}
lat = Math.max(-85, Math.min(85, lat));
phi = THREE.MathUtils.degToRad(90 - lat);
theta = THREE.MathUtils.degToRad(lon);
camera.position.x = 100 * Math.sin(phi) * Math.cos(theta);
camera.position.y = 100 * Math.cos(phi);
camera.position.z = 100 * Math.sin(phi) * Math.sin(theta);
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
animate();
使用CSS3实现简单360全景
对于性能要求不高的场景,可以使用CSS3变换:

<div class="panorama-container">
<div class="panorama-image"></div>
</div>
<style>
.panorama-container {
width: 100%;
height: 100vh;
perspective: 1000px;
overflow: hidden;
}
.panorama-image {
width: 200%;
height: 100%;
background-image: url('panorama.jpg');
background-size: cover;
transform-style: preserve-3d;
transform: rotateY(0deg);
transition: transform 0.5s ease-out;
}
</style>
<script>
const panorama = document.querySelector('.panorama-image');
let rotation = 0;
document.addEventListener('mousemove', (e) => {
const x = e.clientX / window.innerWidth;
rotation = x * 180;
panorama.style.transform = `rotateY(${rotation}deg)`;
});
</script>
使用PhotoSphereViewer库
PhotoSphereViewer是一个专门用于展示360度全景图像的库:
// 引入库
import { Viewer } from 'photo-sphere-viewer';
// 初始化查看器
const viewer = new Viewer({
container: document.getElementById('viewer'),
panorama: 'panorama.jpg',
size: {
width: '100%',
height: '100vh'
},
navbar: [
'autorotate',
'zoom',
'fullscreen'
],
defaultZoomLvl: 50,
autorotateDelay: 3000,
autorotateSpeed: '0.5rpm'
});
全景图像准备注意事项
全景图像应为等距柱状投影格式(equirectangular projection) 推荐分辨率为2:1比例(如6000×3000像素) 确保图像无缝连接,避免明显接缝 可使用Photoshop或PTGui等软件处理原始图像
性能优化建议
压缩全景图像以减少加载时间 考虑使用多分辨率切片技术 移动设备上考虑降低渲染质量 添加加载进度指示器 实现自适应分辨率以匹配设备性能






