Vue项目中使用three.js外部引入obj模型

本文记录了一位开发者在Vue2项目中应用three.js库加载obj模型的过程,遇到的问题及解决方案。通过学习和实践,成功实现了模型的展示和交互功能,尽管没有引入材质,但模型已经能够正常显示。对于初学者来说,这是一个关于前端3D建模和交互学习的实战案例。
摘要由CSDN通过智能技术生成

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

然后开始了学习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>

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

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值