-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageMagnifier.js
More file actions
74 lines (65 loc) · 1.91 KB
/
ImageMagnifier.js
File metadata and controls
74 lines (65 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { useState } from 'react';
const ImageMagnifier = ({
src,
className,
width,
height,
alt,
magnifierHeight = 200,
magnifierWidth = 200,
zoomLevel = 1.5
}) => {
const [showMagnifier, setShowMagnifier] = useState(false);
const [[imgWidth, imgHeight], setSize] = useState([0, 0]);
const [[x, y], setXY] = useState([0, 0]);
const mouseEnter = (e) => {
const el = e.currentTarget;
const { width, height } = el.getBoundingClientRect();
setSize([width, height]);
setShowMagnifier(true);
}
const mouseLeave = (e) => {
e.preventDefault();
setShowMagnifier(false);
}
const mouseMove = (e) => {
const el = e.currentTarget;
const { top, left } = el.getBoundingClientRect();
const x = e.pageX - left - window.scrollX;
const y = e.pageY - top - window.scrollY;
setXY([x, y]);
};
return <div className="relative inline-block">
<img
src={ src }
className={ className }
width={ width }
height={ height }
alt={ alt }
onMouseEnter={ (e) => mouseEnter(e) }
onMouseLeave={ (e) => mouseLeave(e) }
onMouseMove={ (e) => mouseMove(e) }
/>
<div
style={{
display: showMagnifier ? '' : 'none',
position: 'absolute',
pointerEvents: 'none',
height: `${magnifierHeight}px`,
width: `${magnifierWidth}px`,
opacity: '1',
border: '1px solid lightgrey',
backgroundColor: 'white',
borderRadius: '5px',
backgroundImage: `url('${src}')`,
backgroundRepeat: 'no-repeat',
top: `${y - magnifierHeight / 2}px`,
left: `${x - magnifierWidth / 2}px`,
backgroundSize: `${imgWidth * zoomLevel}px ${imgHeight * zoomLevel}px`,
backgroundPositionX: `${-x * zoomLevel + magnifierWidth / 2}px`,
backgroundPositionY: `${-y * zoomLevel + magnifierHeight / 2}px`,
}}
/>
</div>
};
export default ImageMagnifier;