VUE3使用three.js显示3D模型
<template>
<div id="container"></div>
</template>
<script setup>
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
const { ref, onMounted } = Vue;
const container = ref(null);
onMounted(() => {
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 controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('./draco/gltf/');
dracoLoader.setDecoderConfig({ type: 'js' });
dracoLoader.preload();
const gltfLoader = new GLTFLoader();
gltfLoader.setDRACOLoader(dracoLoader);
gltfLoader.load('./models/gltf/Duck/glTF/Duck.gltf', (gltf) => {
scene.add(gltf.scene);
}, (xhr) => {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
}, (error) => {
console.error(error);
});
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update();
}
animate();
});
</script>
<style>
#container {
height: 100vh;
}
</style>
这段代码使用Vue 3的<script setup>
语法,并结合Three.js的GLTFLoader
和DRACOLoader
来加载和显示一个3D模型。在组件被挂载后,它会初始化一个Three.js场景,相机,渲染器和控件,并加载一个GLB格式的3D模型。加载完成后,模型被添加到场景中,并进行渲染。这个例子简洁明了,并展示了如何在Vue 3中集成Three.js的基本步骤。
评论已关闭