svg-pan-zoom平移/缩放到任何对象

时间:2018-08-25 23:04:39

标签: javascript svg

我正在使用svg-pan-zoom代码https://github.com/ariutta/svg-pan-zoom制作某种svg地图,现在是时候添加一项功能,以便在单击时平移和缩放到svg的艺术元素事件。但是,我不确定如何使用panBy()函数来获取所需的svg艺术作品:我尝试在要平移的组上使用getBBox()并将其与panZoomInstance.getPan一起使用()和getSizes()信息,但我的实验无法完成。 我想完成与示例相同的动画之王(http://ariutta.github.io/svg-pan-zoom/demo/simple-animation.html),但将视口居中放置在项目上。

1 个答案:

答案 0 :(得分:2)

在所有可能的情况下,我都能弄清楚这部分!

function customPanByZoomAtEnd(amount, endZoomLevel, animationTime){ // {x: 1, y: 2}
  if(typeof animationTime == "undefined"){
      animationTime =   300; // ms
  }
  var animationStepTime = 15 // one frame per 30 ms
    , animationSteps = animationTime / animationStepTime
    , animationStep = 0
    , intervalID = null
    , stepX = amount.x / animationSteps
    , stepY = amount.y / animationSteps;

  intervalID = setInterval(function(){
    if (animationStep++ < animationSteps) {
      panZoomInstance.panBy({x: stepX, y: stepY})
    } else {
      // Cancel interval
      if(typeof endZoomLevel != "undefined"){
        var viewPort = $(".svg-pan-zoom_viewport")[0];
        viewPort.style.transition = "all " + animationTime / 1000 + "s ease";
        panZoomInstance.zoom(endZoomLevel);
        setTimeout(function(){
            viewPort.style.transition = "none";
            $("svg")[0].style.pointerEvents = "all"; // re-enable the pointer events after auto-panning/zooming.
                    panZoomInstance.enablePan();
                    panZoomInstance.enableZoom();
                    panZoomInstance.enableControlIcons();
                    panZoomInstance.enableDblClickZoom();
                    panZoomInstance.enableMouseWheelZoom();
        }, animationTime + 50);
      }
      clearInterval(intervalID)
    }
  }, animationStepTime)
}

function panToElem(targetElem) {

    var initialSizes = panZoomInstance.getSizes();
    var initialLoc = panZoomInstance.getPan();
    var initialBounds = targetElem.getBoundingClientRect();
    var initialZoom = panZoomInstance.getZoom();
    var initialCX = initialBounds.x + (initialBounds.width / 2);
    var initialCY = initialBounds.y + (initialBounds.height / 2);

    var dX = (initialSizes.width / 2) - initialCX;
    var dY = (initialSizes.height / 2) - initialCY;

  customPanByZoomAtEnd({x: dX, y: dY}, 2, 700);
}

关键是要计算panZoomInstance.getSizes()中的视口宽度和高度的中心与目标元素的客户端边界矩形的中心之间的差。

现在,问题正在尝试制作动画缩放。现在,我已经在平移动画的末尾使用命令将其缩放到指定位置,并设置了一些CSS以使缩放平滑过渡。一段时间后,css将被删除,因此正常的缩放和平移不受影响。在尝试使缩放动画成为步进动画时,它总是看起来会缩放到超过预期的最大点。

相关问题