目录
一、案例截图
二、安装Three.js
三、代码实现
四、Gitee源码
一、案例截图
二、安装Three.js
npm install three
三、代码实现
模型资源我是放在public文件夹下面的:
完整代码:
<template><div><div ref="container"></div></div>
</template><script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
export default {name: "HomeView",data() {return {scene: null,camera: null,renderer: null,model: null,controls: null,width: window.innerWidth,height: window.innerHeight,};},mounted() {this.initThreeJs();this.loadModel();this.animate();},beforeDestroy() {if (this.renderer) {this.renderer.dispose();}},methods: {initThreeJs() {// 初始化场景this.scene = new THREE.Scene();// this.scene.background = new THREE.Color(0xffffff); // 白色背景// 设置相机this.camera = new THREE.PerspectiveCamera(75, this.width / this.height, 0.1, 5000);// 设置相机初始位置this.camera.position.set(0, 0.3, 1); // x = 0, y = 5, z = 10,可以根据需要调整这些值// 设置相机旋转角度(以弧度为单位)this.camera.rotation.x = THREE.MathUtils.degToRad(-30); // 绕x轴旋转 -30度this.camera.rotation.y = THREE.MathUtils.degToRad(0); // 绕y轴旋转 0度this.camera.rotation.z = THREE.MathUtils.degToRad(0); // 绕z轴旋转 0度// 创建渲染器this.renderer = new THREE.WebGLRenderer();this.renderer.setSize(this.width, this.height);this.$refs.container.appendChild(this.renderer.domElement);// 添加灯光const ambientLight = new THREE.AmbientLight(0xffffff, 1);this.scene.add(ambientLight);const pointLight = new THREE.PointLight(0xffffff, 1);pointLight.position.set(10, 10, 10);this.scene.add(pointLight);// 添加 OrbitControlsthis.controls = new OrbitControls(this.camera, this.renderer.domElement);this.controls.enableDamping = true; // 启用阻尼this.controls.dampingFactor = 0.25; // 阻尼因子,越大越慢this.controls.enableZoom = true; // 启用缩放},loadModel() {const loader = new GLTFLoader();loader.load('/obj.gltf', // 模型的路径,支持http请求(gltf) => {this.model = gltf.scene;this.scene.add(this.model);},undefined,(error) => {console.error('模型加载错误:', error);});},animate() {requestAnimationFrame(this.animate);if (this.model) {this.model.rotation.y += 0.01; // 让模型旋转}this.renderer.render(this.scene, this.camera);},}
};
</script><style scoped lang="scss"></style>
四、Gitee源码
码云地址:Vue2+Three.js加载并展示一个三维模型