Native JS image magnifier

rendering

.pic-container {
    width: 400px;
    height: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
.pic-container img{
    width: inherit;
    height: inherit;
}
Copy the code
<div class="pic-container">
  <img src="./nhc.jpg" alt="" />
</div>
Copy the code
// Image container
var container = document.getElementsByClassName('pic-container') [0]
/ / picture
var img = container.getElementsByTagName('img') [0]
// Size (the browser version does not support deconstruction syntax sugar, move yourself →_→)
var { width:picWidth, height:picHeight } = img.getBoundingClientRect()
// Image path
var picUrl = img.src
Param {x} x axis * param {y} y axis */
function calcPosition(multiple, x, y) {
    container.style.backgroundSize = `${multiple * picWidth}px ${multiple * picHeight}px`
    container.style.backgroundPosition = ` -${(multiple - 1) * x}px -${(multiple - 1) * y}px`
}
/ / move
img.addEventListener('mouseover'.function() {
    container.style.background = `url(${picUrl}) no-repeat`
    img.style.opacity = 0
})
/ / removed
img.addEventListener('mouseout'.function() {
    container.style.background = ' '
    img.style.opacity = 1
})
/ / move
img.addEventListener('mousemove'.function(e) {
    var { offsetX, offsetY } = e
    calcPosition(2, offsetX, offsetY)
})
Copy the code

Image resources