Vue3使用Three.js导入gltf模型并解决模型为黑色的问题
<template>
<div id="container"></div>
</template>
<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
export default {
name: 'ModelViewer',
mounted() {
const container = document.getElementById('container');
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, container.offsetWidth / container.offsetHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(container.offsetWidth, container.offsetHeight);
container.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
const loader = new GLTFLoader();
loader.load('path/to/your/model.gltf', (gltf) => {
scene.add(gltf.scene);
}, undefined, (error) => {
console.error(error);
});
// 添加环境光源
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// 添加平行光源
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
camera.position.z = 5;
const animate = function () {
requestAnimationFrame(animate);
controls.update(); // 使相机控制更新
renderer.render(scene, camera);
};
animate();
}
}
</script>
<style>
#container {
width: 100vw;
height: 100vh;
overflow: hidden;
}
</style>
这段代码使用Vue 3和Three.js加载一个gltf模型,并解决了模型为黑色的问题。首先,我们在<script>
标签中导入了必要的Three.js组件,并在mounted
生命周期钩子中初始化了场景、相机、渲染器和模型加载器。我们还添加了环境光源和平行光源来改善场景的光照。最后,我们启动了一个循环来更新相机控制并渲染场景。
评论已关闭