最近我在學習使用
React配合Three.js來搭建一個可以瀏覽720全景圖片的項目
實現的是加載一張 2:1 的720全景
分享一下我的創建過程
一、搭建框架並安裝需要的插件
npx create-react-app parano // 創建一個 React 項目
npm install -S typescript // 安裝 typescript,這個是類型輔助插件,與全景項目關系不大
npm install -S @types/three // 安裝 typescript 支持的 three.js 插件
二、創建 Pano 組件
Pano 組件用來加載720全景圖
import React from 'react'
import * as THREE from 'three' // 引入 Three.js 插件
import banner from './img/playground.jpg' // 引入全景圖
// props 類型聲明接口
interface MyProps {
}
// state 類型聲明接口
interface MyState {
}
class Pano extends React.Component<MyProps, MyState> {
renderer: any = new THREE.WebGLRenderer() // 創建一個渲染器
scene: any = new THREE.Scene() // 創建一個場景
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) // 創建一個攝像機
geometry = new THREE.SphereBufferGeometry(100, 60, 40) // 創建一個球形的容器,用於貼全景圖上去
material: any // 貼圖材質
mesh: any
constructor(props: any) {
super (props)
this.state = {}
}
componentDidMount () {
this.geometry.scale(-1, 1, 1)
let texture = new THREE.TextureLoader().load(banner)
this.material = new THREE.MeshBasicMaterial({map: texture})
this.mesh = new THREE.Mesh(this.geometry, this.material)
this.renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(this.renderer.domElement)
this.scene.add(this.mesh)
this.camera.position.z = 0
window.addEventListener('resize', this.onWindowResize, false)
this.animate()
}
// 實現窗口大小改變的時候改變全景圖的顯示大小
onWindowResize = () => {
this.camera.aspect = window.innerWidth / window.innerHeight
this.camera.updateProjectionMatrix()
this.renderer.setSize(window.innerWidth, window.innerHeight)
}
// 逐幀渲染
animate = () => {
requestAnimationFrame(this.animate)
this.mesh.rotation.y += 0.001
this.renderer.render(this.scene, this.camera)
}
render () {
return (
<div></div>
)
}
}
export default Pano
三、將 Pano 組件添加到 App 組件中
import React from 'react';
import './App.css';
import Pano from './pano';
function App() {
return (
<div className="App">
<Pano />
</div>
);
}
export default App;
此時在項目目錄中執行 npm run start 即可看到效果
我也是個攝影愛好者,之前自己拍攝過學校的720全景項目,現在想學習一下搭建一個720全景展示的網頁,以后就美滋滋啦~
后續還會繼續深入學習貼熱點圖等技術,加油啦!
