Vue使用Three.js 渲染glb、gltf模型
要在Vue中使用Three.js渲染glb或gltf模型,你需要安装three
和@types/three
,并创建一个Three.js场景,导入模型,并将其添加到DOM中。以下是一个简单的例子:
- 安装Three.js:
npm install three
- 安装Three.js类型定义:
npm install @types/three
- 创建Vue组件:
<template>
<div ref="threeContainer"></div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
export default defineComponent({
setup() {
const threeContainer = ref<HTMLElement | null>(null);
let camera: THREE.PerspectiveCamera;
let scene: THREE.Scene;
let renderer: THREE.WebGLRenderer;
let loader: GLTFLoader;
onMounted(() => {
if (threeContainer.value) {
const width = threeContainer.value.clientWidth;
const height = threeContainer.value.clientHeight;
camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.position.z = 5;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
threeContainer.value.appendChild(renderer.domElement);
loader = new GLTFLoader();
loader.load(
'path/to/your/model.glb', // 模型路径
(gltf) => {
scene.add(gltf.scene);
},
(xhr) => {
console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
},
(error) => {
console.error(error);
}
);
animate();
}
});
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
return { threeContainer };
}
});
</script>
<style>
/* 确保容器充满整个父元素 */
#threeContainer {
width: 100%;
height: 100%;
}
</style>
确保替换path/to/your/model.glb
为你的模型实际路径。这个例子使用了Three.js的GLTFLoader
来加载glb或gltf模型,并在Vue组件挂载后开始渲染动画。
评论已关闭