如何使用鼠标中轮按钮拖动Openseadrago画布

时间:2018-11-20 06:19:38

标签: javascript javascript-events mouse fabricjs openseadragon

我正在使用带有fabric.js覆盖的Openseadragon库。我有一种情况,我想拖动画布,但要用鼠标中键按下而不是鼠标主按钮。谁能帮我得到想要的行为?

2 个答案:

答案 0 :(得分:1)

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;
    }
  }
});

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

答案 1 :(得分:0)

扩展@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;
    }
  }
});