vue+threejs实现3D模型预览(包含模型缩放、平移、清晰度调整)
<template>
<div class="model-viewer">
<div id="three-d-viewer" ref="threeDViewer"></div>
</div>
</template>
<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
export default {
name: 'ModelViewer',
data() {
return {
camera: null,
scene: null,
renderer: null,
model: null
};
},
methods: {
initThreeJS() {
const width = this.$refs.threeDViewer.clientWidth;
const height = this.$refs.threeDViewer.clientHeight;
this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
this.camera.position.z = 5;
this.scene = new THREE.Scene();
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setSize(width, height);
this.$refs.threeDViewer.appendChild(this.renderer.domElement);
const loader = new GLTFLoader();
loader.load('path/to/your/model.glb', (gltf) => {
this.model = gltf.scene;
this.scene.add(this.model);
});
},
animate() {
requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
}
},
mounted() {
this.initThreeJS();
this.animate();
}
};
</script>
<style scoped>
.model-viewer {
width: 100%;
height: 80vh;
position: relative;
}
#three-d-viewer {
width: 100%;
height: 100%;
}
</style>
这个代码实例展示了如何在Vue组件中初始化Three.js以及加载一个3D模型,并在组件的mounted
生命周期钩子中开始动画循环。它包括了基本的3D相机、场景、渲染器和模型加载,并且可以通过调整样式来实现模型的缩放、平移和清晰度的调整。
评论已关闭