Uniapp中three.js初使用(加载fbx或者glb)
<template>
<view class="content">
<view id="container" class="container">
</view>
</view>
</template>
<script>
export default {
data() {
return {
// 初始化three.js相关对象
camera: null,
scene: null,
renderer: null,
model: null,
};
},
onReady() {
this.initThree();
// 加载模型,这里以fbx为例
this.loadFbxModel('path/to/your/model.fbx');
},
methods: {
initThree() {
// 初始化three.js的相机、场景和渲染器
let width = window.innerWidth;
let height = window.innerHeight;
this.camera = new THREE.PerspectiveCamera(70, width / height, 0.01, 10);
this.camera.position.z = 0.5;
this.scene = new THREE.Scene();
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setSize(width, height);
this.renderer.setClearColor(0xffffff);
let container = document.getElementById('container');
container.appendChild(this.renderer.domElement);
// 添加灯光
let ambientLight = new THREE.AmbientLight(0x666666);
this.scene.add(ambientLight);
let directionalLight = new THREE.DirectionalLight(0xdfebff);
directionalLight.position.set(50, 20, 50);
this.scene.add(directionalLight);
},
loadFbxModel(url) {
const loader = new THREE.FBXLoader();
loader.load(url, (object) => {
this.model = object;
this.scene.add(this.model);
this.animate();
}, (xhr) => {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
}, (error) => {
console.error('An error happened', error);
});
},
animate() {
requestAnimationFrame(this.animate);
this.model.rotation.y += 0.01;
this.renderer.render(this.scene, this.camera);
}
}
};
</script>
<style>
.container {
width: 100%;
height: 100%;
position: relative;
}
</style>
这段代码展示了如何在Uniapp中初始化three.js环境,并加载一个fbx模型。注意,你需要替换'path/to/your/model.fbx'为你的模型文件路径。此外,你可以根据需要添加对glTF模型的加载支持,只需替换FBXLoader
为GLTFLoader
,并相应地调整文件路径和模型添加到场景的代码。
评论已关闭