场景
要实现在页面中简单快速的加载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>