当前位置:首页 > JavaScript

js 实现图片 放大

2026-02-28 21:59:38JavaScript

使用 CSS transform 实现图片放大

通过 CSS 的 transform: scale() 属性可以实现平滑的图片放大效果。结合 JavaScript 监听鼠标事件来触发放大。

const img = document.querySelector('img');
img.addEventListener('mouseenter', () => {
  img.style.transform = 'scale(1.2)';
  img.style.transition = 'transform 0.3s ease';
});
img.addEventListener('mouseleave', () => {
  img.style.transform = 'scale(1)';
});

使用 CSS zoom 属性

zoom 是 CSS 的非标准属性,但在某些场景下可以快速实现放大效果。

document.getElementById('myImage').style.zoom = "150%";

创建放大镜效果

实现类似放大镜的局部放大功能,需要创建一个跟随鼠标的放大区域。

function magnify(imgID, zoom) {
  const img = document.getElementById(imgID);
  const glass = document.createElement("div");
  glass.setAttribute("class", "img-magnifier-glass");
  img.parentElement.insertBefore(glass, img);

  glass.style.backgroundImage = `url('${img.src}')`;
  glass.style.backgroundRepeat = "no-repeat";
  glass.style.backgroundSize = `${img.width * zoom}px ${img.height * zoom}px`;

  const bw = 3; // 边框宽度
  const w = glass.offsetWidth / 2;
  const h = glass.offsetHeight / 2;

  glass.addEventListener("mousemove", moveMagnifier);
  img.addEventListener("mousemove", moveMagnifier);

  function moveMagnifier(e) {
    let pos = getCursorPos(e);
    let x = pos.x;
    let y = pos.y;

    // 防止放大镜超出图片边界
    if (x > img.width - (w / zoom)) x = img.width - (w / zoom);
    if (x < w / zoom) x = w / zoom;
    if (y > img.height - (h / zoom)) y = img.height - (h / zoom);
    if (y < h / zoom) y = h / zoom;

    glass.style.left = `${x - w}px`;
    glass.style.top = `${y - h}px`;
    glass.style.backgroundPosition = `-${(x * zoom) - w + bw}px -${(y * zoom) - h + bw}px`;
  }

  function getCursorPos(e) {
    const a = img.getBoundingClientRect();
    return {
      x: e.pageX - a.left - window.pageXOffset,
      y: e.pageY - a.top - window.pageYOffset
    };
  }
}

使用第三方库

多个成熟的 JavaScript 库可以快速实现图片放大功能:

  1. Zoom.js:轻量级的图片放大库

    new Zooming({
      bgColor: '#000',
      scaleBase: 0.9,
      scaleExtra: 0.5
    }).listen('.img-zoomable');
  2. Lightbox:支持图片放大查看的库

    lightbox.option({
      'resizeDuration': 200,
      'wrapAround': true,
      'fadeDuration': 200
    });
  3. Fancybox:功能丰富的媒体查看器

    $('[data-fancybox]').fancybox({
      buttons: ['zoom', 'close'],
      animationEffect: "fade"
    });

响应式图片放大

针对不同设备实现响应式放大效果,可以结合 CSS 媒体查询和 JavaScript。

function responsiveZoom() {
  const images = document.querySelectorAll('.zoomable');
  const zoomLevel = window.innerWidth < 768 ? 1.5 : 2.0;

  images.forEach(img => {
    img.addEventListener('click', () => {
      img.style.transform = `scale(${zoomLevel})`;
      img.style.transformOrigin = 'center center';
    });
  });
}
window.addEventListener('resize', responsiveZoom);

触摸设备支持

为移动设备添加触摸事件支持的双指缩放功能。

js 实现图片 放大

let initialDistance = null;
const img = document.getElementById('pinch-zoom-img');

img.addEventListener('touchstart', (e) => {
  if (e.touches.length === 2) {
    initialDistance = Math.hypot(
      e.touches[0].clientX - e.touches[1].clientX,
      e.touches[0].clientY - e.touches[1].clientY
    );
  }
});

img.addEventListener('touchmove', (e) => {
  if (e.touches.length === 2 && initialDistance) {
    const currentDistance = Math.hypot(
      e.touches[0].clientX - e.touches[1].clientX,
      e.touches[0].clientY - e.touches[1].clientY
    );
    const scale = currentDistance / initialDistance;
    img.style.transform = `scale(${scale})`;
  }
});

img.addEventListener('touchend', () => {
  initialDistance = null;
});

标签: 图片js
分享给朋友:

相关文章

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEve…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js实现求导

js实现求导

实现数值求导的方法 在JavaScript中实现求导通常采用数值方法,因为JavaScript不是符号计算语言。以下是常见的数值微分方法: 中心差分法 中心差分法提供较高精度的导数近似:…

vue实现图片闪烁

vue实现图片闪烁

实现图片闪烁效果的方法 在Vue中实现图片闪烁效果可以通过CSS动画或JavaScript动态控制样式。以下是几种常见方法: CSS动画实现 通过@keyframes定义闪烁动画,并应用到图片元素上…

js实现吸色

js实现吸色

使用Canvas实现吸色功能 通过Canvas的getImageData方法获取像素颜色数据。创建一个Canvas元素,将目标图像绘制到Canvas上,通过鼠标事件获取坐标对应的颜色值。 c…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…