自定義一個(gè)基礎(chǔ)工具類(lèi),包含基礎(chǔ)場(chǎng)景和相機(jī)設(shè)置、窗口自適應(yīng)赚哗、調(diào)試工具類(lèi)(適用于同一個(gè)項(xiàng)目需要使用多個(gè)場(chǎng)景的情況)
import * as THREE from 'three'
import OrbitControls from '@/lib/tools/orbitControls'
import Stats from '@/lib/tools/stats'
import dat from 'dat.gui'
export default class Stage {
/**
* @param {Boolean} antialias 抗鋸齒
* @param {Boolean} autoRender 自動(dòng)實(shí)時(shí)渲染
* @param {Function} onRender 實(shí)時(shí)渲染回調(diào)
*/
constructor(antialias = true, autoRender = true, onRender) {
this.antialias = antialias
this.scene = new THREE.Scene()
this.camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
)
this.camera.position.z = 5
this.initRender()
// TODO 生產(chǎn)環(huán)境應(yīng)去掉helper
this.initHelper()
this.AddAdaption()
if(autoRender) {
this.render()
}
}
initRender() {
const renderer = this.renderer = new THREE.WebGLRenderer({ antialias: this.antialias })
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(window.devicePixelRatio)
document.body.appendChild(renderer.domElement)
renderer.render(this.scene, this.camera)
}
initHelper() {
this.orbit = new OrbitControls(this.camera, this.renderer.domElement)
this.gui = new dat.GUI()
const stats = this.stats = new Stats()
// 0: fps, 1: ms, 2: mb, 3+: custom
stats.showPanel(0)
document.body.appendChild(stats.dom)
}
render() {
requestAnimationFrame(this.render.bind(this))
this.renderer.render(this.scene, this.camera)
if(typeof this.onRender === 'function') {
this.onRender()
}
if(this.stats) {
this.stats.update()
}
}
/**
* 添加窗口變化自適應(yīng)監(jiān)聽(tīng)
*/
AddAdaption() {
window.addEventListener(
'resize',
function () {
this.camera.aspect = window.innerWidth / window.innerHeight
this.camera.updateProjectionMatrix()
this.renderer.setSize(window.innerWidth, window.innerHeight)
},
false
)
}
}