vue3中使用three.js加载外部模型
在Vue 3中使用Three.js加载外部模型,你可以创建一个Three.js场景,并使用GLTFLoader
来加载glTF格式的模型。以下是一个简单的例子:
- 确保你已经安装了Three.js。
npm install three
- 安装
GLTFLoader
,因为它不是Three.js的核心部分。
npm install three/examples/jsm/loaders/GLTFLoader
- 在你的Vue组件中,创建Three.js场景并加载模型。
<template>
<div ref="threeContainer"></div>
</template>
<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
export default {
name: 'ModelLoader',
mounted() {
this.initThreeJS();
this.loadModel();
},
methods: {
initThreeJS() {
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);
this.$refs.threeContainer.appendChild(renderer.domElement);
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
camera.position.z = 5;
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
this.scene = scene;
this.camera = camera;
this.renderer = renderer;
this.controls = controls;
},
loadModel() {
const loader = new GLTFLoader();
loader.load(
'path/to/your/model.gltf',
(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);
this.controls.update();
}
},
beforeUnmount() {
cancelAnimationFrame(this.animate);
this.$refs.threeContainer.removeChild(this.renderer.domElement);
},
mounted() {
this.animate();
}
};
</script>
<style>
/* 样式按需定制 */
</style>
确保替换path/to/your/model.gltf
为你的模型文件的实际路径。这段代码创建了一个Three.js场景,加载了一个外部的glTF模型,并在Vue组件的mounted
钩子中开始渲染动画循环。在beforeUnmount
钩子中,它取消了动画请求,并清理了Three.js渲染器。
评论已关闭