vue第一次使用three.js遇到的问题

314 阅读2分钟

前言

最近公司有需求要做3d,于是我就开始研究three.js。

模型下载

three.js 官网有提到Sketchfab这个网站,里面有大量免费的3d模型可下载。下载的时候可以选择格式,大部分都是gltf和glb,小部分是obj。下载后解压是这个式的

1681974680671(1).jpg

textures是纹理材质图片文件夹,txt是作者,网站和作品的信息,gltf是我们的模型信息了。有的模型解压后还有bin文件,我没用到。obj格式解压后有的有glt文件有的没有,但是不管有没有,glt文件里永远没有纹理材质图片地址,不知道是不是都是要自己配置。

开始练习

创建一个新的vue项目,这里就不说了。安装three.js npm install three 将模型放入public目录里面后开始写最基本的代码。为什么有这么多是因为我太菜了一直在坑里出不来。

1681974264834.jpg

我把主要的代码贴出来:

      import * as THREE from 'three';
      import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
      // 场景
      this.scene = new THREE.Scene();
      this.scene.background = new THREE.Color(0xbfe3dd);
      this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
      this.camera.position.set(5, 2, 8);
      this.render = new THREE.WebGLRenderer();
      this.render.setPixelRatio(window.devicePixelRatio);
      this.render.outputEncoding = THREE.sRGBEncoding;
      this.render.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(this.render.domElement);
      const pmremGenerator = new THREE.PMREMGenerator(this.render);
      this.scene.environment = pmremGenerator.fromScene(new RoomEnvironment(), 0.04).texture;

      // 控制器
      this.controls = new OrbitControls(this.camera, this.render.domElement);
      this.controls.target.set(0, 1, 0);
      this.controls.update();
      this.controls.enablePan = false;
      this.controls.enableDamping = true;
      this.render.render(this.scene, this.camera);

场景搞里头,摄像机搞里头,控制器搞里头,咕噜咕噜出锅了,本次就讲到这里了。

怎么可能!!!导入模型

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

let that = this;
let loader = new GLTFLoader()
loader.load('assets/scene2.gltf', function (obj) {
        that.scene.add(obj.scene)
        that.animate()
      }, function (e) {
        console.log(e)
      }, function (e) {
        console.log(e)
      })
//下面都是基础方法,不说了
animate() {
    requestAnimationFrame(this.animate); 
    this.controls.update()
    this.render.render(this.scene, this.camera);
}

PS: 为什么路径是assets而不是public,因为这是threeJS定义的

load方法我用了四个参数:第一个是模型的路径,第二个是回调函数,第三个是加载中的回调,第四个是失败回调。 ok写完收工npm run serve启动:

tmd不写了,问题复现不出来了!