three.js控制glb模型旋转
时间: 2024-06-04 15:04:52 浏览: 149
使用Three.js控制glb模型旋转可以通过以下步骤来实现:
1. 首先需要引入Three.js库和GLTFLoader.js库,可以在html中添加以下代码:
```
<script src="https://cdn.bootcdn.net/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/three.js/r128/loaders/GLTFLoader.js"></script>
```
2. 加载glb模型并创建场景和相机:
```
const loader = new THREE.GLTFLoader();
let scene, camera;
loader.load('path/to/model.glb', function(gltf) {
scene = gltf.scene;
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
scene.add(camera);
scene.rotation.x = Math.PI / 2; // 旋转场景以便更好地查看模型
animate();
});
```
3. 创建一个渲染器并将其添加到DOM中:
```
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
```
4. 创建一个函数来更新场景:
```
function animate() {
requestAnimationFrame(animate);
scene.rotation.y += 0.01; // 控制模型的旋转速度
renderer.render(scene, camera);
}
```
5. 最后在HTML中添加一个canvas元素,将渲染器的dom元素赋值给canvas元素的context属性:
```
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
canvas.getContext('2d').drawImage(renderer.domElement, 0, 0);
</script>
```
阅读全文