three.js加载3d模型gltf
时间: 2023-09-10 13:04:49 浏览: 212
使用three.js加载glTF模型非常简单,你可以按照以下步骤进行操作:
1. 引入three.js和GLTFLoader.js文件。
```html
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/GLTFLoader.js"></script>
```
2. 创建一个场景、相机和渲染器。
```javascript
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
```
3. 加载glTF模型。
```javascript
const loader = new THREE.GLTFLoader();
loader.load('path/to/model.gltf', function(gltf) {
scene.add(gltf.scene);
}, undefined, function(error) {
console.error(error);
});
```
4. 渲染场景。
```javascript
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
```
完整的代码如下所示:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Load glTF Model with Three.js</title>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/GLTFLoader.js"></script>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const loader = new THREE.GLTFLoader();
loader.load('path/to/model.gltf', function(gltf) {
scene.add(gltf.scene);
}, undefined, function(error) {
console.error(error);
});
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```
请注意,上述代码中的路径"path/to/model.gltf"应该替换为你自己的glTF模型的路径。
阅读全文