对应教程
three.js docs
通过此教程,掌握了如何通过载入GLTF格式的外部模型,除此之外,还可以在如其他obj格式。都演示练习。
练习代码
GLTF格式模型导入
参考并删减此样例的内容:three.js-master/examples/webaudio_orientation.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>导入模型demo</title>
</head>
<body>
<div id="info"></div>
<script type="importmap">
{
"imports": {
"three": "./three.js-master/build/three.module.js",
"three/addons/": "./three.js-master/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from "three"
import { GLTFLoader } from "three/addons/loaders/GLTFloader.js"
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// 基本场景创建
const scene = new THREE.Scene();
scene.background = new THREE.Color( 0xa0a0a0 );
const camera = new THREE.PerspectiveCamera(75, // 视野FOV,代表能看到的视野角度
window.innerWidth/window.innerHeight, // 长宽比,代表被压扁的程度
0.1, // 近界面,比近界面近的物体不会被渲染
1000 // 远界面,比远界面远的物体不会被渲染
);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement)
camera.position.set(3,2,3);
// 载入模型
const gltfLoader = new GLTFLoader();
gltfLoader.load( './three.js-master/examples/models/gltf/BoomBox.glb', function ( gltf ) {
const boomBox = gltf.scene;
// boomBox.position.set( 0, 0.2, 0 );
boomBox.scale.set( 20, 20, 20 ); // x,y,z轴的缩放比例,如果太小,看不到。
scene.add( boomBox );
renderer.setAnimationLoop( animate );
} );
// 设置控制轨道
const controls = new OrbitControls( camera, renderer.domElement );
controls.target.set( 0, 0.1, 0 );
controls.update();
controls.minDistance = 0.5;
controls.maxDistance = 10;
controls.maxPolarAngle = 0.5 * Math.PI;
// 渲染立方体
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera)
}
animate();
</script>
</body>
</html>
安利一个开源项目
threejs-learning/src/common/threeModules/Viewer.js at public · tingyuxuan2302/threejs-learning · GitHub