場景
要實現在頁面中簡單快速的加載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-objref="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>