Vue中使用vue-3d-model实现加载3D模型预览展示

场景

要实现在页面中简单快速的加载3D模型用于产品展示。

实现效果如下:

注:

博客:
霸道流氓气质-CSDN博客

实现

3D模型技术方案对比

这里用于快速展示简单3d模型。

3D模型文件下载

可下载的网站较多,比如:

Sketchfab - The best 3D viewer on the web

++3D Models for Free - Free3D.com++

这里去free3d进行模型文件下载

这里下载obj和mtl格式的。

下载之后将其放在项目的public/models/demo目录下

加载模型显示

安装依赖

复制代码
npm install vue-3d-model --save

新建页面,修改代码

复制代码
<template>
  <el-dialog :visible.sync="visible"  :title="title" style="height: 500px;">
      <!-- 3D模型区 -->
      <div class="model-part">
        <model-obj
          ref="modelViewer"
          :src="modelPath"
          :mtl="mtlPath"
          :rotation="modelRotation"
          :scale="modelScale"
          backgroundColor="#050a30"
          @on-load="handleModelLoad"
          @on-error="handleModelError"
          class="model-container"
        ></model-obj>
      </div>
  </el-dialog>
</template>
 
<script>
import { ModelObj } from 'vue-3d-model';
 
export default {
  components: { ModelObj },
  data() {
    return {
      visible: true,
      title: '标题',
      // 模型配置
      // 确保路径指向正确的模型文件
      modelPath: process.env.BASE_URL  + 'models/demo/aa.obj?t='  + Date.now(),
      mtlPath: process.env.BASE_URL  + 'models/demo/aa.mtl?t='  + Date.now(),
      modelRotation: {
        x: -0.3,
        y: 0.5,
        z: 0
      },
      modelScale: { x: 0.8, y: 0.8, z: 0.8 }, // 统一缩放比例
      loadFailed: false
    }
  },// 在mounted中添加验证代码
  mounted() {
    fetch(this.modelPath)
      .then(res => res.text())
      .then(text => {
        console.log(' 文件头信息:', text.substring(0,  50));
        console.assert(!text.includes('<!DOCTYPE  html>'), '错误:加载到HTML文件而非OBJ模型');
      });
  },
  methods: {
    handleModelLoad() {
      console.log('3D 模型加载完成');
      // 可添加模型加载成功后的回调逻辑
    },
    handleModelError(error) {
      console.error(' 模型加载失败:', error);
      this.loadFailed  = true;
    }
  }
}
</script>
 
<style scoped>
/* 模型容器样式 */
.model-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 300px;
}
 
 
/* 备用加载样式 */
.model-fallback {
  text-align: center;
  padding-top: 30%;
  color: rgba(255, 255, 255, 0.5);
}
.model-fallback i {
  font-size: 40px;
  display: block;
  margin-bottom: 10px;
}

</style>
相关推荐
西洼工作室32 分钟前
CSS高效开发三大方向
前端·css
昔人'35 分钟前
css`font-variant-numeric: tabular-nums` 用来控制数字的样式。
前端·css
铅笔侠_小龙虾1 小时前
动手实现简单Vue.js ,探索Vue原理
前端·javascript·vue.js
sniper_fandc3 小时前
Axios快速上手
vue.js·axios
哟哟耶耶3 小时前
Starting again-02
开发语言·前端·javascript
Apifox.3 小时前
Apifox 9 月更新| AI 生成接口测试用例、在线文档调试能力全面升级、内置更多 HTTP 状态码、支持将目录转换为模块
前端·人工智能·后端·http·ai·测试用例·postman
Kitasan Burakku3 小时前
Typescript return type
前端·javascript·typescript
叁佰万3 小时前
前端实战开发(一):从参数优化到布局通信的全流程解决方案
前端
笔尖的记忆3 小时前
js异步任务你都知道了吗?
前端·面试
光影少年4 小时前
react生态
前端·react.js·前端框架