0%

01 起步 - 旋转的立方体 - Threejs入门

使用 Threejs 框架写一个最简单的立方体效果,了解场景(Scene), 相机(Camera), 渲染器(Renderer)的基本概念和使用方式。 [ 练一练 ] [ 看一看 ]

这次使用的是常见的透视投影相机(PerspectiveCamera),该方法的四个参数分别为 视野角度、宽高比、摄像机允许观察的最近距离、摄像机允许观察的最远距离。

示例代码

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
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()

演示效果