效果图
组件
js代码
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { ZoomInOutlined, ZoomOutOutlined,RedoOutlined,UndoOutlined,ArrowLeftOutlined,ArrowRightOutlined,CloseOutlined} from '@ant-design/icons'
import './index.css';
class PhotoPreview extends React.Component {
constructor(props) {
super(props);
this.state = {
bigUrl: props.bigUrl === '' ? props.url : props.bigUrl,
tool: Object.assign(PhotoPreview.defaultProps.tool, props.tool),
imgIndex: props.imgIndex,
imgs: props.imgs,
loadEl: true, // loading元素显示隐藏
figureEl: false, // 生成图片预览元素
imgOriginalWidth: 0, // 当前大图默认宽度值
imgOriginalHeight: 0, // 当前大图默认高度值
imgAttr: {
// 大图的地址及描述
src: '',
alt: '',
},
imgParentStyle: {
// 大图父级div元素样式
width: '0px',
height: '0px',
},
rotateDeg: 0, // 图片旋转角度
increaseNum: 20, // 图片放大时距离空隙
};
// 获取相关元素
this.bigImgRef = React.createRef();
this.ppiRef = React.createRef();
}
// 预览图片超出window宽或高的处理
beyondWindow = () => {
const { imgParentStyle, rotateDeg, increaseNum } = this.state;
const iWidth = parseFloat(imgParentStyle.width) + increaseNum * 2;
const iHeight = parseFloat(imgParentStyle.height) + increaseNum * 2;
const ppiEl = this.ppiRef.current;
let ips = imgParentStyle;
if (rotateDeg % 360 === 90 || rotateDeg % 360 === 270) {
if (iHeight > window.innerWidth) {
ips = { ...ips, left: `${(iHeight - iWidth) / 2 + increaseNum}px` };
} else {
ips = { ...ips, left: 'auto' };
}
if (iWidth > window.innerHeight) {
ips = { ...ips, top: `${(iWidth - iHeight) / 2 + increaseNum}px` };
} else {
ips = { ...ips, top: 'auto' };
}
} else if (
(rotateDeg % 360 === -90 && iWidth > iHeight) ||
(rotateDeg % 360 === -270 && iWidth > iHeight)
) {
// 如果是-90或-270,并且图片宽大于高的话,那么则需要做兼容处理
let left = 'auto';
let top = 'auto';
if (iHeight > ppiEl.clientWidth) {
left = `${-(iHeight / 2) + increaseNum * 2}px`;
}
if (iWidth > ppiEl.clientHeight) {
top = `${iHeight / 2 + increaseNum / 2}px`;
}
ips = { ...ips, left: `${left}`, top: `${top}` };
} else if (
(rotateDeg % 360 === -90 && iHeight > iWidth) ||
(rotateDeg % 360 === -270 && iHeight > iWidth)
) {
// 如果是-90或-270,并且图片高大于宽的话,那么则需要做兼容处理
let left = 'auto';
let top = 'auto';
if (iHeight > ppiEl.clientWidth) {
left = `${iWidth / 2}px`;
}
if (iWidth > ppiEl.clientHeight) {
top = `${-(iWidth / 2) + increaseNum * 2}px`;
}
ips = { ...ips, left: `${left}`, top: `${top}` };
} else {
if (iWidth > window.innerWidth) {
ips = { ...ips, left: `${increaseNum}px` };
} else {
ips = { ...ips, left: 'auto' };
}
if (iHeight > window.innerHeight) {
ips = { ...ips, top: `${increaseNum}px&