使用鼠标滚轮做图片缩放

使用 Canvas 显示图片,将鼠标悬浮在“图片”(CanvasContainer)内,滚动鼠标滚轮来进行图片缩放。

基于以下教程开发

1.对指定 dom 加入事件监听

<div id="canvasContainer" style="width:100%;text-align:center;overflow:auto">
  <canvas id="canvas" width="1" height="1" tabindex="1">
    Sorry, your browser does not support HTML5 Canvas functionality which is
    required for this application.
  </canvas>
</div>
const canvasContainer = document.getElementById("canvasContainer");
// for firefox
if (canvasContainer.addEventListener) {
  canvasContainer.addEventListener(
    "DOMMouseScroll",
    (e) => {
      this.scrollFunc(e, "dom");
    },
    false
  );
}
// for non firefox
canvasContainer.onmousewheel = (e) => {
  this.scrollFunc(e, "dom");
};

2.事件处理函数

function scrollFunc(e, dom) {
  let delta = 0;
  const event = e || window.event;
  if (event.altKey && event.ctrlKey && dom) {
    return false;
  } else if (!event.altKey && !event.ctrlKey && !dom) {
    return false;
  }
  if (event.wheelDelta) {
    //IE、chrome浏览器使用的是wheelDelta,并且值为“正负120”
    delta = event.wheelDelta / 120;
    if (window.opera) {
      delta = -delta; //因为IE、chrome等向下滚动是负值,FF是正值,为了处理一致性,在此取反处理
    }
  } else if (event.detail) {
    delta = -event.detail / 3;
  }
  if (delta) {
    handleScroll(delta);
  }
}

function handleScroll(delta) {
  if (delta < 0) {
    // 向下滚动
    zoomIn(); // 在上一章有这个函数的实现方式
  } else {
    // 向上滚动
    zoomOut(); // 在上一章有这个函数的实现方式
  }
}

3.记得在此页面销毁前去除事件监听

不去掉监听会影响其他页面的显示和操作效果

if (document.addEventListener) {
  document.addEventListener("DOMMouseScroll", {}, false);
} //W3C
window.onmousewheel = document.onmousewheel = {};
const canvasContainer = document.getElementBy("canvasContainer");
if (canvasContainer && canvasContainer.addEventListener){
  canvasContainer.addEventListener("DOMMouseScroll", {}false);
  canvasContainer.onmousewheel = {};
}

可通过按钮、框选、滚轮滚动来放大缩小图片的示例:

Sorry, your browser does not support HTML5 Canvas functionality which is required for this application.