Vue集成three.js,加载glb、gltf类型的3d模型
要在Vue项目中集成three.js并加载glb或gltf类型的3D模型,你需要按照以下步骤操作:
- 安装three.js和相关加载器:
npm install three
npm install --save three/examples/jsm/loaders/GLTFLoader
- 在Vue组件中引入three.js和GLTFLoader,并创建场景、相机和渲染器:
<template>
<div ref="container"></div>
</template>
<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
export default {
name: 'ThreeModel',
mounted() {
this.initThreeJS();
this.loadModel();
},
methods: {
initThreeJS() {
const container = this.$refs.container;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, container.offsetWidth / container.offsetHeight, 0.1, 1000);
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(container.offsetWidth, container.offsetHeight);
container.appendChild(this.renderer.domElement);
// 添加灯光
const ambientLight = new THREE.AmbientLight(0x404040);
this.scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
this.scene.add(directionalLight);
this.camera.position.z = 5;
},
loadModel() {
const loader = new GLTFLoader();
loader.load(
'path/to/your/model.glb', // 模型路径
(gltf) => {
this.scene.add(gltf.scene);
},
(xhr) => {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
(error) => {
console.error(error);
}
);
},
animate() {
requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
}
},
beforeDestroy() {
// 清理场景以防内存泄漏
this.scene.clear();
this.renderer.forceContextLoss();
this.renderer.context = null;
this.renderer.domElement = null;
this.renderer = null;
}
};
</script>
<style>
/* 样式按需添加 */
</style>
在上述代码中,你需要将'path/to/your/model.glb'替换为你的模型文件路径。initThreeJS
方法初始化场景、相机和渲染器,并将渲染器的DOM元素挂载到Vue模板中的<div>
元素上。loadModel
方法使用GLTFLoader
加载模型,并将其添加到场景中。animate
方法循环调用requestAnimationFrame
来更新渲染帧。
在beforeDestroy
钩子中,你应当清理场景以防止内存泄漏。
确保你的Vue组件模板中有一个<div>
元素来作为three.js渲染的容器。
评论已关闭