magnifier-react
Version:
商城放大镜React组件,图片放大镜
137 lines (134 loc) • 4.17 kB
JSX
import React from "react"
class Magnifier extends React.Component {
state={
show: false,
moveOffset: {
top: 0,
left: 0
},
moveBox: this.props.moveBox,
zoomOffset: {
left: 0,
top: 0
},
img: {
height: 0,
width: 0
}
}
handleLoadImage=(e) => {
e.preventDefault()
const img = e.target
if (img.naturalHeight && img.naturalWidth) {
this.setState({
img: {
height: img.naturalHeight,
width: img.naturalWidth
}
})
}
}
handleMove=(e) => {
e.preventDefault()
const {moveBox, img} = this.state
let Target = e.currentTarget.getBoundingClientRect()
let cx = e.clientX - e.currentTarget.getBoundingClientRect().left
let cy = e.clientY - e.currentTarget.getBoundingClientRect().top
let boxWidth = e.currentTarget.getBoundingClientRect().width
let boxHeight = e.currentTarget.getBoundingClientRect().height
let moveBoxX = cx - moveBox.width / 2
let moveBoxY = cy - moveBox.height / 2
if (moveBoxX <= 0) {
moveBoxX = 0
}
if (moveBoxY <= 0) {
moveBoxY = 0
}
if (moveBoxX >= boxWidth - moveBox.width) {
moveBoxX = boxWidth - moveBox.width
}
if (moveBoxY >= boxHeight - moveBox.height) {
moveBoxY = boxHeight - moveBox.height
}
let scaleX = moveBoxX / (boxWidth - moveBox.width)
let scaleY = moveBoxY / (boxHeight - moveBox.height)
let zoomX = -(img.width - this.props.showBox.width) * scaleX
let zoomY = -(img.height - this.props.showBox.height) * scaleY
this.setState({
show: true,
moveOffset: {
left: moveBoxX,
top: moveBoxY
},
zoomOffset: {
left: zoomX,
top: zoomY
}
})
}
handleLeave=(e) => {
e.preventDefault()
this.setState({
show: false
})
}
render() {
const {show, moveOffset, moveBox, zoomOffset} = this.state
const {src, mainBox, showBox} = this.props
return (
<div
style={{
position: "relative",
height: mainBox.height,
width: mainBox.width,
}}
onMouseMove={this.handleMove}
onMouseLeave={this.handleLeave}
>
<img
style={{
height: mainBox.height,
width: mainBox.width,
}}
src={src}
/>
<div
style={{
position: "absolute",
display: show ? "block" : "none",
height: moveBox.height,
width: moveBox.width,
left: moveOffset.left,
top: moveOffset.top,
background: moveBox.background ? moveBox.background : "blue",
opacity: moveBox.opacity ? moveBox.opacity : "0.3",
cursor: moveBox.cursor ? moveBox.cursor : "move"
}}
>
</div>
<div
style={{
position: "absolute",
overflow: "hidden",
display: show ? "block" : "none",
zindex:10,
height: showBox.height,
width: showBox.width,
top: showBox.top ? showBox.top : 0,
left: showBox.left ? showBox.left : mainBox.width+6
}}
>
<img src={src}
style={{
position: "absolute",
top: zoomOffset.top,
left: zoomOffset.left
}}
onLoad={this.handleLoadImage}
/>
</div>
</div>
)
}
}
export default Magnifier