最近我在學習使用 React
配合 Three.js
來搭建一個可以瀏覽720全景圖片的項目
實現的是加載一張 2:1 的720全景
分享一下我的創建過程
一、搭建框架并安裝需要的插件
1
2
3
|
npx create-react-app parano // 創建一個 React 項目 npm install -S typescript // 安裝 typescript,這個是類型輔助插件,與全景項目關系不大 npm install -S @types/three // 安裝 typescript 支持的 three.js 插件 |
二、創建 Pano 組件
Pano 組件用來加載720全景圖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
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 組件中
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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
即可看到效果
到此這篇關于使用 React 和 Threejs 創建一個VR全景項目的過程詳解的文章就介紹到這了,更多相關 React 和 Threejs 創建VR全景內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_44242330/article/details/108047024