- 引入 Three.js 库和 GLTFLoader 模块
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r122/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three/examples/js/loaders/GLTFLoader.js"></script>
- 创建场景、相机、渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
- 加载 glTF 模型
const loader = new THREE.GLTFLoader();
loader.load(
'model.gltf',
function (gltf) {
scene.add(gltf.scene);
},
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
function (error) {
console.log('An error happened');
}
);
- 渲染场景和模型
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
以上是 Three.js 加载 glTF 的详细步骤,根据需要可以做更多的设置和调整。