0%

02 要有光 - 场景中添加光源 - 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
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.MeshStandardMaterial() // 设置标准网格材质
const boxMesh = new THREE.Mesh(boxGeo, boxMtr)
scene.add(boxMesh)

// 创建环境光
const ambLight = new THREE.AmbientLight()
// 创建平行光
const dirLight = new THREE.DirectionalLight()
// 设置平行光位置
dirLight.position.set(5, 5, 5)
// 添加到场景中
scene.add(ambLight, dirLight)

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

animation()

演示效果