0%

04 可大可小 - 自适应页面 和 双击页面全屏效果 - Threejs入门

通过监听页面大小的变动,动态修改渲染器大小、相机宽高比和投影矩阵。 [ 练一练 ] [ 看一看 ]

示例代码

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
import * as THREE from 'three'
const $app = document.getElementById('app')

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(50, window.innerWidth/window.innerHeight, 1, 1000)
camera.position.z = 10

const renderer = new THREE.WebGLRenderer({
antialias: true
})

renderer.setSize(window.innerWidth, window.innerHeight)
$app.appendChild(renderer.domElement)

const boxGeo = new THREE.BoxGeometry(1, 1, 1)
const boxMtr = new THREE.MeshBasicMaterial()
const boxMesh = new THREE.Mesh(boxGeo, boxMtr)
scene.add(boxMesh)

function animation() {
boxMesh.rotation.y += 0.01
renderer.render(scene, camera)
requestAnimationFrame(animation)
}

animation()

// 监听页面尺寸变化
window.addEventListener('resize', () => {
// 重新设置渲染器大小
renderer.setSize(window.innerWidth, window.innerHeight)
// 重新设置相机宽高比
camera.aspect = window.innerWidth / window.innerHeight
// 重新设置相机投影矩阵
camera.updateProjectionMatrix()
})

// 监听鼠标双击事件
window.addEventListener('dblclick', () => {
// 判断为全屏时退出全屏,否则进入全屏
if(document.fullscreenElement) {
document.exitFullscreen()
} else {
renderer.domElement.requestFullscreen()
}
})

演示效果