You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

放大镜效果进阶问题:缩放倍数增大时显示半径异常

问题:放大镜缩放倍数增大后显示半径小于预期

在实现兼具响应式且支持原图滤镜的放大镜效果时,编写了如下代码,但遇到了显示异常的问题:

代码实现

HTML

<div class="container">
  <img src="https://i.sstatic.net/Z4aOFrum.jpg" alt="bg">
  <div class="glass"></div>
</div>

CSS

.container {
  position: absolute;
  width: 40%;
  height: fit-content;
  left: 8%;
  top: 20%;
  border: 1px dashed grey;
  overflow: hidden;
  cursor: none;

  &> img {
    width: 100%; 
    height: auto; 
    display: block;
  }

  &:hover .glass {
    opacity: 1;
  }

  .glass {
    position: absolute;
    left: var(--left);
    top:  var(--top);
    width: 100%;
    height: auto;
    clip-path: circle(var(--clip-path));
    pointer-events: none;
    transition: opacity 0.2s;
    opacity: 0;

    img {
      width: calc(var(--zoom) * 100%);
      display: block;
    }
  }
}

JavaScript

// The magnification factor; an integer greater than 1
const zoom = 3; 
// The radius of the glass (as a percentage of the image's width)
// a number between 1 and 100, inclusive
const radius = 25;

const container = document.querySelector('.container');
const glass = document.querySelector('.glass');
const { style } = glass;
style.setProperty('--zoom', zoom);

// Add the magnified image as a clone
// This way it'll include any filter applied to the original image
const img = container.querySelector('img').cloneNode();
glass.append(img);

container.addEventListener('mousemove', (e) => {
  // ISSUE: The diameter of the glass is, as the magnification gets bigger, smaller than expected
  const clipPath = `${radius / zoom}% at ${e.offsetX * zoom}px ${e.offsetY * zoom}px`;
  
  style.setProperty('--clip-path', clipPath);
  style.setProperty('--left', `${(zoom - 1 ) * -e.offsetX}px`)
  style.setProperty('--top', `${(zoom - 1 ) * -e.offsetY}px`)
});

遇到的问题

当缩放倍数(zoom)为2时,放大镜显示半径符合设置值(例如radius设为25时,显示为原图的50%),但增大zoom后,放大镜显示半径比预期更小,尽管放大后的图片尺寸更大。

内容的提问来源于stack exchange,提问作者Andrew Foulds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:15:09