0%

10 加载模型 - Threejs入门

使用 GLTFLoader 就可以加载常见的gltf模型了~ [ 练一练 ] [ 看一看 ]

示例代码

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
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

// 导入gltf加载器
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'

const $app = document.getElementById('app')

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
0.1,
1000
)
camera.position.set(0, 0, 10)

const renderer = new THREE.WebGLRenderer({
antialias: true,
})
renderer.setSize(window.innerWidth, window.innerHeight)
$app.appendChild(renderer.domElement)

// 实例化加载器
const loader = new GLTFLoader()

// 加载gltf模型
loader.load('/htmls/three.js/models/立方体.glb', (gltf) => {
scene.add(gltf.scene)
})

// 设置光源
const light = new THREE.DirectionalLight(null, 2)
light.position.set(20, 20, 30)
scene.add(new THREE.AmbientLight(null, 2), light)

new OrbitControls(camera, renderer.domElement)

function animate() {
requestAnimationFrame(animate)
renderer.render(scene, camera)
}
animate()

演示效果