Magnifier
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Magnifying Glass Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="img-container">
<img id="magnify-image" src="https://images.pexels.com/photos/4554155/pexels-photo-4554155.jpeg?auto=compress&cs=tinysrgb&w=600" alt="Image to magnify">
<div id="magnifying-glass"></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS
/* Styles for the container */
.container {
position: relative;
margin: 0 auto;
}
/* Styles for the image container */
.img-container {
position: fixed;
width: 300px;
height: 200px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
overflow: hidden;
}
/* Styles for the image */
#magnify-image {
width: 100%;
display: block;
}
/* Styles for the magnifying glass */
.magnifier-glass {
position: absolute;
border: 3px solid #000;
border-radius: 50%;
cursor: none;
pointer-events: none;
width: 80px; /* Size of the magnifying glass */
height: 80px;
background-repeat: no-repeat;
background-size: 200%; /* Adjust according to magnification level */
background-position: center;
}
/* Additional styles if needed */
JavaScript
function magnify(magnifiedImg, zoom) {
let img = magnifiedImg;
let pos, x, y, glass, container;
const imgRect = img.getBoundingClientRect(); // Get image dimensions
glass = document.createElement('div'); // Create actual magnifying glass
glass.classList.add('magnifier-glass');
img.parentElement.insertBefore(glass, img);
container.appendChild(glass);
glass.style.backgroundImage = `url(${img.src})`; // Set background image
glass.style.backgroundRepeat = 'no-repeat';
glass.style.backgroundSize = `${img.width * zoom}px ${img.height * zoom}px`;
const w = glass.offsetWidth / 2;
const h = glass.offsetHeight / 2;
img.addEventListener( 'pointerleave', () => (glass.style.display = 'none'));
img.addEventListener('pointerenter', () => (glass.style.display = 'block'));
img.addEventListener('mousemove', moveMagnifier); // Updates glass based on cursor positio
glass.addEventListener('mousemove', moveMagnifier);
function moveMagnifier(e) {
e.preventDefault();
pos = getCursorPos(e); // Calls function to get cursor position
x = pos.x;
y = pos.y;
glass.style.left = `${x - w}px`; // Centers glass position over cursor
glass.style.top = `${y - h}px`;
glass.style.backgroundPosition = `-${x * zoom - w}px -${y * zoom - h}px`;
}
function getCursorPos(e) {
let xPos = e.clientX - imgRect.left; // Gets cursor position based on image position
let yPos = e.clientY - imgRect.top;
return { x: xPos, y: yPos };
}
}
document.addEventListener('DOMContentLoaded', () => {
const zoom = 3;
const img = document.getElementById('magnify-image');
magnify(img, zoom);
});