安装three.js:
npm install three
页面部分代码:
<div style="width: 100%; height: 300px; position: relative;"><div style="height: 200px; background-color: white; width: 100%; position: absolute; top: 0;"><div id="threeView" style="width: 100%; height: 200px; background-color: #f1f1f1; position: absolute; bottom: 0;"></div>
</div>
js部分代码:
initThree(){console.log('打印场景API',THREE.Scene)scene=new THREE.Scene();var ambient = new THREE.AmbientLight(0xffffff,5);scene.add(ambient) //添加环境光var width = window.innerWidthvar height = 300var k = width/height;camera = new THREE.PerspectiveCamera(45,k,1,1000);camera.position.set(0,0,20);camera.lookAt(new THREE.Vector3(0, 0, 0));renderer = new THREE.WebGLRenderer({antialias: true});renderer.setSize(width, height);renderer.setClearColor(0XECF1F3, 0);const element = document.getElementById('threeView');element.appendChild(renderer.domElement);renderer.render(scene, camera);this.animate();},createControls() {controls = new OrbitControls(camera, renderer.domElement)controls.enableZoom = true;},// 修改为仅使用STLLoader加载模型的方法loadSTLModel() {let loader = new GLTFLoader();loader.load('scene.gltf', function(gltf) {// 使用加载的几何体创建材质和网格console.log(loader)// const material = new THREE.MeshPhongMaterial({// color: 0xffffff// });// const mesh = new THREE.Mesh(geometry, material);const mesh = gltf.scene;scene.add(mesh);const rotationXDegrees = -90 // 模型沿X轴旋转45度const rotationXRadians = THREE.MathUtils.degToRad(rotationXDegrees);mesh.rotation.y = rotationXRadians;// 添加模型到场景scene.add(mesh);// 调整模型大小mesh.scale.set(3, 3, 3);// 设置模型位置mesh.position.set(0, 0, 0);const animations = gltf.animations;if (animations && animations.length > 0) {// 创建一个动画混合器this.mixer = new THREE.AnimationMixer(mesh);// 查找你想播放的动画,例如假设第一个动画是开门动画const animationAction = this.mixer.clipAction(animations[0]);this.start=this.mixer.clipAction(animations[0]);animationAction.stop(); // 默认播放动画}}.bind(this));}
部分效果图: