实现效果
代码
react项目
- 引入方式可选其一
1.在html中引入
<script type="module" src="https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js"></script>
- npm 或者 yarn安装
yarn add @google/model-viewer
- index.js
import React, { useState, useEffect } from 'react';
import { Spin } from 'antd';
import s from './index.less'
import model from './images/3d/three.glb';
export default function Three(props) {
const [loading, setLoading] = useState(true)
useEffect(() => {
if (props.show) {
const modelViewerPle = document.querySelector('#model');
modelViewerPle.addEventListener('progress', (event) => {
const loaded = event.detail.totalProgress;
if (loaded === 1) {
setLoading(false)
}
console.log('loading-progress', loaded);
});
modelViewerPle.addEventListener('load', async () => {
console.log('load',)
})
}
}, [props.show])
return (<div className={s.threeCon}>
<div className={s.modelCon}>
{
loading ? <div className={s.loadingCon}>
<Spin
delay={300}
tip="加载中..."
size='large'
fullscreen
spinning
></Spin>
</div> : null}
<model-viewer
id='model'
src={model}
alt="A 3D model of an astronaut"
// ar
// auto-rotate
camera-controls
max-camera-orbit="auto 90deg auto"
style={{ width: '100%', height: '100%' }}
></model-viewer>
</div>
</div>
)
}
index.less
.threeCon {
width: 100%;
height: 100%;
margin: 0 auto;
.modelCon {
width: 100%;
height: 100%;
position: relative;
.loadingCon {
width: 100%;
height: 100%;
background-color: rgba(15, 70, 94, 1);
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 9;
}
}
}
本项目使用webpack,所以需要加下配置
先需要安装 file-loader 插件
export.default = {
module: {
rules: [
...
{
oneOf: [
{
test: /\.(glb|gltf)(\?.*)?$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'models', // 输出路径
// limit: 2048, // 2kb
}
}
]
}
]
}
]
}
}
标签:modelViewerPle,index,viewer,100%,import,model,glb
From: https://www.cnblogs.com/ZerlinM/p/18547787