How to Create an Image Magnifier Using JavaScript

If you've ever browsed a shopping site, you've probably come across image magnification features. It lets you zoom in on a specific area of ​​an image for easier viewing. Incorporating this little important feature can greatly improve the user experience of your website.

Building an image magnifier in a seamless manner can be a challenge. But walking through these steps will help you create your own image magnifier from scratch without relying on third-party plugins.

When to Use Image Magnifiers in Web Projects?

The image magnifier comes in handy when you're building projects with lots of images. As mentioned earlier, image magnifiers are popular on shopping sites because sometimes users may need to take a closer look at a product before deciding if it's worth buying.

Customers completely rely on the information and visuals provided by the website to evaluate the quality, function and appearance of the product. However, still images alone may not always provide sufficient clarity or facilitate a full product evaluation.

In a traditional store, customers can physically touch a product, take a close look at it, and assess suitability before making a purchase. Image Magnifier attempts to recreate this experience by providing users with a sort of scrutiny and inspection in a virtual way.

Image magnifiers also come in handy if you're building a photo gallery app, since magnifying a specific part of an image is an important feature.

Build Image Magnifier

The code used in this project is available for free under the MIT license in the GitHub code repository.

Create a folder, add index.html file, style.css file and main.js file in this folder. Add this boilerplate code to index.html:

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <title>Image Magnifier</title>
 <link rel="stylesheet" href="style.css" />
</head>

<body>
</body>

</html>

In the body tag, create a div element with class name "header". Then in the "header" div, add an h1 heading element to display the title of the image magnifier.

You can customize the text as needed. Next, include two span elements that provide instructions for using the magnifying glass and display the current zoom level to the user.

After the header section, create a div element with class name "container". Inside this div, add another div element with the class "magnifier" and hide it with the class "hidden".

This element will represent the magnifying glass image. Then, add a script tag with the "src" attribute set to "/main.js".

<body>
 <div class="header">
 <h1>Image Magnifier</h1>

 <span>Press <strong>Arrow Up</strong> or <strong>Arrow Down</strong> to
 increase or decrease athe zoom level.</span>

 <span>Zoom Level: <strong class="zoom-level">1</strong></span>
 </div>

 <div class="container">
 <div class="magnifier hidden"></div>
 </div>

 <script src="/main.js"></script>
</body>

Replace the code in the style.css file with the following code. You can also use a CSS preprocessor like Less if needed.

:root {
 --magnifier-width: 150;
 --magnifier-height: 150;
}

body {
 display: flex;
 flex-direction: column;
 align-items: center;
}

.container {
 width: 400px;
 height: 300px;
 background-size: cover;
 background-image: url("https://cdn.pixabay.com/photo/2019/03/27/15/24/animal-4085255_1280.jpg");
 background-repeat: no-repeat;
 position: relative;
 cursor: none;
}

.magnifier {
 border-radius: 400px;
 box-shadow: 0px 11px 8px 0px #0000008a;
 position: absolute;
 width: calc(var(--magnifier-width) * 1px);
 height: calc(var(--magnifier-height) * 1px);
 cursor: none;
 background-image: url("https://cdn.pixabay.com/photo/2019/03/27/15/24/animal-4085255_1280.jpg");
 background-repeat: no-repeat;
}

span {
 display: block;
}

.header {
 display: flex;
 flex-direction: column;
 align-items: center;
}

.hidden {
 visibility: hidden;
}

div > span:nth-child(3) {
 font-size: 20px;

In the main.js file, use the document.querySelector method to retrieve the HTML elements with the class names "magnifying glass" and "container", and assign them to the variable magnifier and the variable container respectively.

Then, use the getComputedStyle function to retrieve the width and height of the magnifying glass element, and then use the substring and indexOf methods to extract the values ​​from the returned string.

Assign the extracted width to the variable magnifierWidth and the extracted height to the variable magnifierHeight.

let magnifier = document.querySelector(".magnifier");
let container = document.querySelector(".container");

let magnifierWidth = getComputedStyle(magnifier).width.substring(
  0,
   getComputedStyle(magnifier).width.indexOf("p")
);

let magnifierHeight = getComputedStyle(magnifier).width.substring(
   0,
  getComputedStyle(magnifier).height.indexOf("p")
);

Next, set variables for the zoom level, maximum zoom level, and position of the cursor and magnifying glass images.

let zoomLevelLabel = document.querySelector(".zoom-level");
let zoom = 2;
let maxZoomLevel = 5;
let pointerX;
let pointerY;
let magnifyX;
let magnifyY;

In the code block above, both pointerX and pointerY represent the position of the cursor on the X and Y axes.

Now, define two helper functions: getZoomLevel (returns the current zoom level) and getPointerPosition (returns an object with the cursor's x and y coordinates).

function getZoomLevel() {
 return zoom;
}

function getPointerPosition() {
 return { x: pointerX, y: pointerY }
}

Next, create an updateMagImage function that creates a new MouseEvent object with the current cursor position and dispatches it to the container element. This function is responsible for updating the magnifying glass image.

function updateMagImage() {
 let evt = new MouseEvent("mousemove", {
 clientX: getPointerPosition().x,
 clientY: getPointerPosition().y,
 bubbles: true,
 cancelable: true,
 view: window,
 });

 container.dispatchEvent(evt);
}

You should now add an event listener to the window object for the "keyup" event, which adjusts the zoom level when the user presses the "ArrowUp" or "ArrowDown" keys.

The callback function on the "keyup" event is also responsible for updating the zoom level label and triggers the updateMagImage function.

window.addEventListener("keyup", (e) => {
 if (e.key === "ArrowUp" && maxZoomLevel - Number(zoomLevelLabel.textContent) !== 0) {
 zoomLevelLabel.textContent = +zoomLevelLabel.textContent + 1;
 zoom = zoom + 0.3;
 updateMagImage();
 }

 if (e.key === "ArrowDown" && !(zoomLevelLabel.textContent <= 1)) {
 zoomLevelLabel.textContent = +zoomLevelLabel.textContent - 1;
 zoom = zoom - 0.3;
 updateMagImage();
 }
});

Then, add an event listener to the container element for the "mousemove" event.

In the callback function, add the functionality to remove the "hidden" class from the magnifying glass element to make it visible, and calculate the position of the mouse relative to the container, taking into account page scrolling.

The function should also set the transform style of the magnifying glass to the calculated position, and determine the background size and position of the magnifying glass image based on the zoom level and mouse position.

container.addEventListener("mousemove", (e) => {
 magnifier.classList.remove("hidden");
 let rect = container.getBoundingClientRect();
 let x = e.pageX - rect.left;
 let y = e.pageY - rect.top;

 x = x - window.scrollX;
 y = y - window.scrollY;

 magnifier.style.transform = `translate(${x}px, ${y}px)`;
 const imgWidth = 400;
 const imgHeight = 300;

 magnifier.style.backgroundSize =
 imgWidth * getZoomLevel() + "px " + imgHeight * getZoomLevel() + "px";

 magnifyX = x * getZoomLevel() + 15;
 magnifyY = y * getZoomLevel() + 15;

 magnifier.style.backgroundPosition = -magnifyX + "px " + -magnifyY + "px";
});

Then add another event listener to the container element, but this time the event listener should listen for the "mouseout" event and add the "hidden" class back to the magnifying glass element when the mouse leaves the container area.

container.addEventListener("mouseout", () => {
 magnifier.classList.add("hidden");
});

Finally, add event listeners to the window object for the "mousmove" event that updates the x and y position of the cursor.

window.addEventListener("mousemove", (e) => {
 pointerX = e.clientX;
 pointerY = e.clientY;
});

That's it! You've successfully built an image magnifier using plain JavaScript.

How does Image Magnifier improve user experience?

By allowing users to zoom in on a specific area of ​​an image, a magnifier allows them to see product details more clearly.

This enhanced level of visual exploration instills confidence in users as they make informed decisions. This helps increase conversion rates and improve customer retention.

Guess you like

Origin blog.csdn.net/pantouyuchiyu/article/details/132085356