公司项目需要往数字孪生等概念,实现模型展示数据,并且模型能交互

然后开始了学习three.js的路程,了解基本概念以后,外部引入obj后缀类型模型一直报错,模型加载老是失败。

看了很多博客以及官网案例很少有Vue2的案例,最终还是成功引入了模型

<template>
  <div></div>
</template>

<script>
import * as Three from "three";
import OrbitControls from "three-orbitcontrols";
import { OBJLoader } from "three-obj-mtl-loader";
export default {
  data() {
    return {
      // 相机
      camera: null,
      // 场景
      scene: null,
      // 渲染器对象
      renderer: null,
      // 材质对象
      mesh: null,
      controls: null,
      modelList: [
        "4号楼楼体-一层",
        "4号楼楼体-二层",
        "4号楼楼体-三层",
        "4号楼楼体-四层",
        "4号楼楼体-五层",
      ],
    };
  },
  methods: {
    // 初始化
    init() {
      let that = this;
      // 相机位置
      let width = window.innerWidth;
      let height = window.innerHeight;
      // 创建场景
      this.scene = new Three.Scene();
      let k = width / height;
      let s = 150;
      this.camera = new Three.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
      this.camera.position.set(80, 100, 60);
      this.camera.lookAt(new Three.Vector3(1, 80, 0));
      this.scene.add(this.camera);
      // 创建点光源
      let light = new Three.DirectionalLight(0xffaaff);
      light.position.set(80, 100, 50);
      this.scene.add(light);
      // 创建渲染器
      this.renderer = new Three.WebGLRenderer({ antialias: true });
      this.renderer.setSize(width, height);
      document.body.appendChild(this.renderer.domElement);
      // 创建控件对象
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.addEventListener("change", this.animate);
      that.modelList.slice(0, 5).forEach((current) => {
        that.loadObj(current);
      });
    },
    // 创建obj模型
    loadObj(current) {
      let that = this;
      let objloader = new OBJLoader();
      objloader.load(`static/model/${current}.obj`, function(obj) {
        that.mesh = obj;
        that.scene.add(that.mesh);
        that.animate();
      });
    },
    // 创建动画
    animate() {
      this.renderer.render(this.scene, this.camera);
    },
  },
  mounted() {
    this.init();
  },
};
</script>
<style scoped>
</style>

 没有引入材质,不过模型确实出来了。学习之路,任重而道远。

Logo

前往低代码交流专区

更多推荐