UNPKG

image-magnifier-react

Version:

React图片放大镜组件,鼠标经过会显示放大镜

89 lines (82 loc) 2.61 kB
/* * Author rhys.zhao * Date 2022-01-27 11:34:47 * LastEditors rhys.zhao * LastEditTime 2022-03-03 21:14:33 * Description 图片放大镜组件 */ import React, { useState, useRef } from 'react'; import styles from './index.scss'; const Magnifier = (props) => { const { image, width = '100%', zoom = 2, magnifierWidth = 100, magnifierHeight = 100, borderWidth = 2, borderColor = 'white' } = props; const [left, setLeft] = useState(0); const [top, setTop] = useState(0); const [imageZoom, setImageZoom] = useState(1); const [magnifierVisible, setMagnifierVisible] = useState(false); const [magnifierImageLeft, setMagnifierImageLeft] = useState(false); const [magnifierImageTop, setMagnifierImageTop] = useState(false); const imageDom = useRef(); const onHover = (e) => { const { offsetX, offsetY } = window.event; const mouseTop = offsetY; const mouseLeft = offsetX; const { width, naturalWidth } = imageDom.current; // 计算相对于原图的缩放比例,以便于正确缩放 const imageZoom = (zoom * width) / naturalWidth; setImageZoom(imageZoom); // 计算放大镜的坐标 const left = mouseLeft - magnifierWidth / 2 - borderWidth; const top = mouseTop - magnifierHeight / 2 - borderWidth; setLeft(left); setTop(top); // 计算放大镜里面图片的偏移 const magnifierImageLeft = magnifierWidth / 2 + borderWidth - zoom * mouseLeft; const magnifierImageTop = magnifierHeight / 2 + borderWidth - zoom * mouseTop; setMagnifierImageLeft(magnifierImageLeft); setMagnifierImageTop(magnifierImageTop); }; return ( <div style={{ width }} className={styles.imageWrap} onMouseOut={() => { setMagnifierVisible(false); }} onMouseOver={() => { !magnifierVisible && setMagnifierVisible(true); }}> <img src={image} className={styles.image} ref={imageDom} onMouseMove={onHover} /> <div className={styles.magnifier} style={{ display: magnifierVisible ? 'block' : 'none', left: left, top: top, width: magnifierWidth, height: magnifierHeight, borderWidth, borderColor }}> <img src={image} className={styles.magnifierImage} style={{ left: magnifierImageLeft, top: magnifierImageTop, transform: `scale(${imageZoom})`, transformOrigin: 'left top' }} /> </div> </div> ); }; export default Magnifier;