如何使用鼠标中轮按钮拖动 Openseadragon canvas

How to drag an Openseadragon canvas with mouse middle wheel button

我正在使用带有 fabricjs 覆盖的 Openseadragon 库。我有一种情况,我想拖动 canvas 但不是鼠标主按钮,我想通过按下鼠标中键来拖动它。谁能帮我得到想要的行为?

OpenSeadragon 没有用于此的标志,但您可以使用 MouseTracker 轻松构建它。这是一个例子(根据记忆编码,未经测试,但它应该给你一个想法)。

var drag;

var mouseTracker = new OpenSeadragon.MouseTracker({
  element: viewer.container, 
  nonPrimaryPressHandler: function(event) {
    if (event.button === 1) { // Middle
      drag = { 
        lastPos: event.position.clone()
      };
    }
  },
  moveHandler: function(event) {
    if (drag) {
      var deltaPixels = drag.lastPos.minus(event.position);
      var deltaPoints = viewer.viewport.deltaPointsFromPixels(deltaPixels);
      viewer.viewport.panBy(deltaPoints);
      drag.lastPos = event.position.clone();
    }
  },
  nonPrimaryReleaseHandler: function(event) {
    if (event.button === 1) {
      drag = null;
    }
  }
});

编辑:我在上面的示例代码中有一个错误;已修复。

扩展@iangilman 的回答...

为了在拖动时在 MouseTracker 元素外释放中间按钮时改善用户体验,导致 nonPrimaryReleaseHandler 永远不会被调用,指针可以被捕获...像这样:

var trackerElement = viewer.container;
var drag;

function capturePointer(event) {
  if (OpenSeadragon.MouseTracker.havePointerCapture) {
    if (OpenSeadragon.MouseTracker.havePointerEvents) {
      // Can throw InvalidPointerId
      try {
        trackerElement.setPointerCapture(event.originalEvent.pointerId);
      } catch () {
        //
      }
    } else {
        trackerElement.setCapture(true);
    }
  }
}

function releasePointer(event) {
  if (OpenSeadragon.MouseTracker.havePointerCapture) {
    if (OpenSeadragon.MouseTracker.havePointerEvents) {
      // Can throw InvalidPointerId
      try {
        trackerElement.releasePointerCapture(event.originalEvent.pointerId);
      } catch () {
        //
      }
    } else {
        trackerElement.releaseCapture();
    }
  }
}

var mouseTracker = new OpenSeadragon.MouseTracker({
  element: trackerElement,
  nonPrimaryPressHandler: function(event) {
    if (event.button === 1) { // Middle
      capturePointer(event);
      drag = {
        lastPos: event.position.clone()
      };
    }
  },
  moveHandler: function(event) {
    if (drag) {
      var deltaPixels = drag.lastPos.minus(event.position);
      var deltaPoints = viewer.viewport.deltaPointsFromPixels(deltaPixels);
      viewer.viewport.panBy(deltaPoints);
      drag.lastPos = event.position.clone();
    }
  },
  nonPrimaryReleaseHandler: function(event) {
    if (event.button === 1) {
      releasePointer(event);
      drag = null;
    }
  }
});