Advertisement

Magnifying Glass Image Zoomer

| by Vladimir | 2 min read | code by Jhey Tompkins
Intermediate

Tech & Dependencies

JavaScript Pug Stylus

Features

  • Pointer Tracking
  • Wheel Zooming
  • Edge Detection

Browser Support

Chrome 80+ Edge 80+ Firefox 75+ Safari 13+

Core

This Magnifying Glass Image Zoomer simulates a physical lens moving over a surface, making it ideal for product detail pages or photography portfolios. Unlike simple CSS transforms, this component uses JavaScript to calculate precise cursor coordinates and synchronizes a zoomed-in background image with a floating SVG overlay.

Core Technique: Coordinate Mapping & CSS Variables

The realism of this effect comes from the mathematical relationship between the “Lens” position and the “Image” translation.

1. Pointer Tracking (Logic)

The JavaScript listens for pointermove events. It calculates the cursor’s position as a percentage relative to the image container (xPercent, yPercent). Importantly, it implements edge detection logic using Math.min and Math.max to prevent the zoomed image from showing white gaps when the lens is near the border.

const update = e => {
  // 1. Calculate cursor position as percentage
  const xPercent = ((x - left) / width) * 100
  
  // 2. Calculate translation for the inner zoomed image
  // Inverse direction to create the "lens" effect
  const xTranslation = (xPercent - 50) * -1
  
  // 3. Update CSS Variables
  VIEWFINDER_IMG.style.setProperty('--x', setX) // Zoomed image pos
  VIEWFINDER.style.setProperty('--x', xPercent)  // Lens pos
}

2. The Visual Layer (CSS)

The CSS uses the variables set by JavaScript to move the elements. The .zoomer__viewfinder (the lens container) follows the mouse, while the .zoomer__viewfinder-img (the zoomed content) moves in the opposite direction to align with the part of the image currently under the lens.

.zoomer__viewfinder {
  /* Moves the lens wrapper */
  left: calc(var(--x, 50) * 1%);
  top: calc(var(--y, 50) * 1%);
}

.zoomer__viewfinder-img {
  /* Scales the inner image based on scroll wheel */
  transform: scale(var(--viewfinder-scale)) 
             translate(calc(var(--x, 0) * 1%), calc(var(--y, 0) * 1%));
}

Browser Support

This snippet relies on standard browser APIs and performs excellently across all modern environments.

Key Technologies:

  • CSS Custom Properties (Variables): Essential for the performance of the animation.
  • Pointer Events (pointermove): Used instead of mousemove for better touch device support.
  • Fetch API: Used to load the random image (can be replaced with static src).
Advertisement