通过监听页面大小的变动,动态修改渲染器大小、相机宽高比和投影矩阵。 [ 练一练 ] [ 看一看 ]
示例代码
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() } })
|
演示效果