项目新需求,要在页面中显示已做好的3D模型,做过技术调研后选择了Threejs三维引擎。demo基本都是独立页面的,自己搞了一下,在vue项目中完美运行了。分享一下
资源引入
npm i three-js
组件内使用
引入:
import * as THREE from "three"; //引入Threejs
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
首先,创建初始化方法:
init() {
this.scene = new THREE.Scene();
this.scene.add(new THREE.AmbientLight(0x404040, 6)); //环境光
this.light = new THREE.DirectionalLight(0xdfebff, 0.45); //从正上方(不是位置)照射过来的平行光,0.45的强度
this.light.position.set(50, 200, 100);
this.light.position.multiplyScalar(0.3);
this.scene.add(this.light);
/**
* 相机设置
*/
let container = document.getElementById("threeContainer");//显示3D模型的容器
this.camera = new THREE.PerspectiveCamera(
70,
container.clientWidth / container.clientHeight,
0.01,
10
);
this.camera.position.z = 1;
/**
* 创建渲染器对象
*/
this.renderer = new THREE.WebGLRenderer({ alpha: true });
this.renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(this.renderer.domElement);
//创建控件对象
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
}
外部模型加载函数:
loadGltf() {
let self = this;
let loader = new GLTFLoader();
//load一个测试模型路径:public/model/zhuozi2.gltf
loader.load("/model/zhuozi2.gltf", function(gltf) {
self.isLoading = false;//关闭载入中效果
self.mesh = gltf.scene;
self.mesh.scale.set(0.4, 0.4, 0.4);//设置大小比例
self.mesh.position.set(0, 0, 0);//设置位置
self.scene.add(self.mesh); // 将模型引入three、
self.animate();
});
}
动画效果:
animate() {
if (this.mesh) {
requestAnimationFrame(this.animate);
// this.mesh.rotation.x += 0.01;
this.mesh.rotation.y += 0.004;
this.renderer.render(this.scene, this.camera);
}
}
在这里插入图片描述