Zoom in on Image Details with Magnifier Lens Effect in JavaScript

Category: Javascript , Zoom | September 5, 2024
Authorbdekraker
Last UpdateSeptember 5, 2024
LicenseMIT
Views613 views
Zoom in on Image Details with Magnifier Lens Effect in JavaScript

This is a JavaScript-powered Magnifier Lens Effect that allows you to apply an interactive magnifying glass effect to any image on your webpage. The magnifier lens always follows the mouse cursor and your users can also adjust the lens size and magnification level with the scroll wheel.

This magnifying glass effect provides a user-friendly way to explore specific areas of images without needing a separate image viewer. Think of e-commerce sites displaying intricate product details, medical websites showcasing high-resolution scans, or even art portfolios allowing viewers to appreciate the nuances of a painting.

How to use it:

1. Add your high-resolution image to the webpage. Don’t forget to assign the ID “magnifiable-image” to this image element. This ID allows the JavaScript to identify and target the image correctly.

<img src="/path/to/your-image.webp" alt="Magnifiable Image" id="magnifiable-image" />

2. Add the following JavaScript snippet to your webpage, either within <script> tags or in a separate JavaScript file. This code creates the magnifying lens element, styles it, and handles the zoom functionality.

The JavaScript code creates a new div element that serves as the magnifying lens. This lens is initially hidden and styled using CSS to resemble a magnifying glass. The code then attaches event listeners to the image.

When the mouse moves over the image, the mousemove listener calculates the position of the lens relative to the mouse cursor and updates the lens’s position on the screen. It also dynamically adjusts the background image of the lens to show a magnified portion of the original image, creating the zoom effect.

The wheel event listener allows users to adjust the size of the lens and the magnification level using the mouse wheel. This provides a more interactive and customizable experience.

// Create the Magnifier Lens
var magnifierLens = document.createElement('div');
magnifierLens.classList.add('magnifier-lens');
document.body.appendChild(magnifierLens); // Append it to the body or a specific container
function setupMagnifier(imageElement) {
    var magnificationFactor = 3; // Adjust magnification level as needed
    var magnifierSize = 200; // Starting size of the magnifier lens
    // Ensure the magnifier lens is styled and prepared
    magnifierLens.style.backgroundRepeat = 'no-repeat';
    magnifierLens.style.pointerEvents = 'none';
    magnifierLens.style.position = 'absolute';
    magnifierLens.style.border = '1px solid #000';
    magnifierLens.style.borderRadius = '50%';
    magnifierLens.style.width = magnifierSize + 'px'; // Diameter of the lens
    magnifierLens.style.height = magnifierSize + 'px'; // Diameter of the lens
    magnifierLens.style.visibility = 'hidden'; // Initially hidden
    magnifierLens.style.boxShadow = '0 0 5px #000'; 
    magnifierLens.style.cursor = 'crosshair';
    // Function to update magnifier lens size
    function updateMagnifierSize(deltaY) {
        // Update magnifier size
        magnifierSize += deltaY > 0 ? -20 : 20;
        magnifierSize = Math.max(100, Math.min(magnifierSize, 400));
        
        // Adjust magnification factor based on lens size
        magnificationFactor = 2 + (magnifierSize - 100) * (5 - 2) / (400 - 100);
        
        magnifierLens.style.width = magnifierSize + 'px';
        magnifierLens.style.height = magnifierSize + 'px';
    
        // Update lens styling for new magnification
        updateLensMagnification();
    }
    function updateLensMagnification() {
        if (!imageElement) return; // Ensure there's an image element to work on
        var bounds = imageElement.getBoundingClientRect();
        var bgPosX = -(magnifierLens.offsetLeft - bounds.left) * magnificationFactor - magnifierLens.offsetWidth / 2;
        var bgPosY = -(magnifierLens.offsetTop - bounds.top) * magnificationFactor - magnifierLens.offsetHeight / 2;
        magnifierLens.style.backgroundSize = `${imageElement.width * magnificationFactor}px ${imageElement.height * magnificationFactor}px`;
        magnifierLens.style.backgroundPosition = `${bgPosX}px ${bgPosY}px`;
        // Trigger reflow
        magnifierLens.offsetHeight;
    }
    imageElement.addEventListener('mousemove', function(e) {
        magnifierLens.style.visibility = 'visible';
        var bounds = e.target.getBoundingClientRect();
        var mouseX = e.clientX - bounds.left;
        var mouseY = e.clientY - bounds.top;
        var lensX = mouseX - (magnifierLens.offsetWidth / 2);
        var lensY = mouseY - (magnifierLens.offsetHeight / 2);
        magnifierLens.style.left = (bounds.left + window.pageXOffset + lensX) + 'px';
        magnifierLens.style.top = (bounds.top + window.pageYOffset + lensY) + 'px';
        var bgPosX = -((mouseX * magnificationFactor) - magnifierLens.offsetWidth / 2);
        var bgPosY = -((mouseY * magnificationFactor) - magnifierLens.offsetHeight / 2);
        magnifierLens.style.backgroundImage = `url('${imageElement.src}')`;
        magnifierLens.style.backgroundSize = `${imageElement.width * magnificationFactor}px ${imageElement.height * magnificationFactor}px`;
        magnifierLens.style.backgroundPosition = `${bgPosX}px ${bgPosY}px`;
        imageElement.style.cursor = 'none'; // Hide the cursor when magnifier is active
    });
    imageElement.addEventListener('wheel', function(e) {
        e.preventDefault(); // Prevent the page from scrolling
        updateMagnifierSize(e.deltaY); // Adjust the magnifier size based on scroll direction
    }, { passive: false });
    imageElement.addEventListener('mouseleave', function() {
        magnifierLens.style.visibility = 'hidden';
        imageElement.style.cursor = 'default'; // Reset the cursor when the mouse leaves
    });
}
// Setup the magnifier on the image
var imageElement = document.getElementById('magnifiable-image');
setupMagnifier(imageElement);

3. You can easily control the initial magnification level and the starting size of the lens by modifying these variables within the JavaScript code:

// Adjust magnification level as needed
var magnificationFactor = 3; 
// Starting size of the magnifier lens
var magnifierSize = 200;

4. Add this CSS to style the magnifying lens. You can adjust the border, border-radius, cursor style, box shadow, and other properties to match your website’s design.

.magnifier-lens {
    position: absolute;
    border: 1px solid #000;
    border-radius: 50%;
    cursor: crosshair;
    box-shadow: 0 0 5px #000;
    pointer-events: none;
    visibility: hidden;
    background-repeat: no-repeat;
}

5. With the code in place, users can now interact with the image. When they hover over the image, the magnifying lens appears. Moving the mouse across the image moves the lens accordingly, providing a magnified view of the area under the lens. Users can also adjust the zoom level by scrolling the mouse wheel while hovering over the image.

You Might Be Interested In:


Leave a Reply