0%

03 自由掌控 - 相机轨道控制器 和 帧率展示 - Threejs入门

轨道控制器(OrbitControls) 是一种摄像机控制器,用鼠标改变不同视角查看场景中的内容。同时增加帧率展示,便于知道运行是否流畅,调试性能的绝佳助手。 [ 练一练 ] [ 看一看 ]

示例代码

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
import * as THREE from 'three'

// 引入轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
// 引入Stats
import Stats from 'three/examples/jsm/libs/stats.module.js'

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)

// 创建轨道控制器, 传入需要控制的相机,和dom元素
new OrbitControls(camera, renderer.domElement)

// 创建stats
const stats = new Stats()
// 将stats放入页面中
$app.appendChild(stats.domElement)

function animation() {
// 实时更新stats信息
stats.update()

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

animation()

演示效果