需求:预览图片,实现图片放缩,图片不可以被复制下载
import React, { useEffect, useRef, useState } from 'react';
import { Modal, Slider, InputNumber, Row, Col } from 'antd';
import styles from './style.less';
const ImageModal = ({ visible, onCancel, initData }) => {
const canvasRef = useRef();
const [zoomValue, setZoomValue] = useState(60)
useEffect(() => {
if (initData) {
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = initData.url;
img.onload = () => {
canvas.width = img.width
canvas.height = img.height
ctx.drawImage(img, 0, 0)
}
}
}, [initData])
const onZoomChange = value => {
setZoomValue(value)
}
return (
<>
<Modal title={initData ? initData.title : '图片查看'}
visible={visible}
centered
bodyStyle={{ padding: 0, backgroundColor: '#c3c3c3' }}
forceRender
footer={<div className={styles.modalFooter}>
<Row>
<Col span={16}>
<Slider
min={1}
max={100}
onChange={onZoomChange}
value={typeof zoomValue === 'number' ? zoomValue : 60}
/>
</Col>
<Col span={8}>
<InputNumber
min={1}
max={100}
bordered={false}
formatter={value => `${value}%`}
parser={value => value.replace('%', '')}
style={{ margin: '0 16px' }}
value={zoomValue}
onChange={onZoomChange}
/>
</Col>
</Row>
</div>}
width='80%'
onCancel={onCancel}>
<div className={styles.imageViewer}>
<canvas ref={canvasRef} style={{ width: `${zoomValue}%` }} className={styles.myCanvas}>
</canvas>
</div>
</Modal>
</>
);
};
export default ImageModal
实现效果: