全景照片加载与浏览
1. 使用Three.js
加载全景照片,往往先想到的是使用天空盒,即将全景照片作为天空盒的贴图
下面的代码是使用Three.js创建天空盒示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body,
canvas {
height: 100%;
width: 100%;
margin: 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three/build/three.module.js",
"three/addons/": "https://unpkg.com/three/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const scene = new THREE.Scene();
const canvas = document.querySelector('#canvas');
const camera = new THREE.PerspectiveCamera(75, canvas.clientWidth / canvas.clientHeight , 0.1, 100000);
camera.position.y = 5;
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer({
canvas: document.querySelector('#canvas')
});
renderer.setSize(window.innerWidth, window.innerHeight, false)
const controls = new OrbitControls( camera, renderer.domElement );
const geometry = new THREE.SphereGeometry(64);
const texture = new THREE.TextureLoader().load("https://photo-sphere-viewer-data.netlify.app/assets/sphere.jpg"); // 这张照片来自photo-sphere-viewer
const sphereMaterial = new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide });
const sphere = new THREE.Mesh(geometry, sphereMaterial);
scene.add(sphere);
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
2. 使用Photo Sphere Viewer
PhotoSphereViewer是基于Three.js二次封装的一个显示Photo Sphere全景照片的JavaScript库,官网:Getting Started | Photo Sphere Viewer (photo-sphere-viewer.js.org)
使用Photo Sphere Viewer可以快速搭建一个全景照片浏览的工具
参考官网示例很容易写一个简单的全景照片的例子
<head>
<!-- for optimal display on high DPI devices -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@photo-sphere-viewer/core/index.min.css" />
</head>
<!-- the viewer container must have a defined size -->
<div id="viewer" style="width: 100%; height: 100%;"></div>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three/build/three.module.js",
"@photo-sphere-viewer/core": "https://cdn.jsdelivr.net/npm/@photo-sphere-viewer/core/index.module.js"
}
}
</script>
<script type="module">
import { Viewer } from '@photo-sphere-viewer/core';
const viewer = new Viewer({
container: document.querySelector('#viewer'),
panorama: 'https://photo-sphere-viewer-data.netlify.app/assets/sphere.jpg',
});
</script>
可以看到,Photo Sphere Viewer还给出了默认控件
3. 参考资料
[1] three.js docs (three3d.cn)
[2] Getting Started | Photo Sphere Viewer (photo-sphere-viewer.js.org)