【问题标题】:Pan/Zoom to specific group ID/getBBox() with d3.behavior.zoom使用 d3.behavior.zoom 平移/缩放到特定组 ID/getBBox()
【发布时间】:2016-02-08 20:04:16
【问题描述】:

我正在尝试使用d3.behavior.zoom() 功能制作交互式平移/缩放 SVG 平面图/地图。我的代码松散地基于Zoom to Bounding Box II

我通过 $.get() 异步加载 svg,然后使用 button.on('click') 处理程序通过元素 ID #g-1101(在 svg 上表示为红色圆圈)获取特定 <g>.getBBox()。然后我想将 svg 的视口居中到#g-1101 的边界框的中间。

作为粗略的尝试,我只是尝试使用g#1101.getBBox().x && .getBBox().y 翻译顶级svg > g。在我看来,我的数学是错误的。

我尝试将 (svg.node().getBBox().width / 2) - scale * g.getBBox().x) 合并到边界框的中点到视口的中心,但它的翻译甚至不在球场上。

代码

(function(){

 var svg, g; $.get('http://layersofcomplexity.com/__fp.svg', function(svg){
   $('body').append($(svg));
   init();
  },'text');

  function init() {

    console.log('init');

   svg = d3.select('svg');
   g = d3.select('svg > g');

    var zoom = d3.behavior.zoom()
    .translate([0, 0])
    .scale(1)
    .scaleExtent([1, 8])
    .on("zoom", zoomed);

    svg
    .call(zoom)
    .call(zoom.event);

    $('.pan').on('click', function(){
//       var id = '#g-1011';
      var scale = 4;
      var bbox = $('#g-1101')[0].getBBox(); 
//       d3.select(id).node().getBBox();
      var x = bbox.x;
      var y = bbox.y;
      // var scale = .9 / Math.max(dx / width, dy / height),
      // var translate = [width / 2 - scale * x, height / 2 - scale * y];
      var width = svg.node().getBBox().width;
      var height = svg.node().getBBox().height;
      var translate = [-scale*x,-scale*y];
      g.transition().duration(750) .call(zoom.translate(translate).scale(scale).event);
    });

  }

  function zoomed() {
    g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

})();

-- EDIT JSBin 坏了--

我错过了什么? JSBin.

【问题讨论】:

  • 不清楚小提琴正在缩放平移是否有特别的东西你在这里看...问题不清楚..
  • 上传 SVG 并制作 JSBin 时,我在朋友的电脑上。显然这一切都搞砸了,所以我只是把它修好了。它现在应该可以工作了。理想情况下,我可以点击Pan 按钮并平移/缩放到g#g-1101
  • JSBin 上什么也没有发生。有意?

标签: javascript d3.js svg zooming


【解决方案1】:

对代码进行一个小改动,将红色标记的g#g-1101居中

  var bbox = $('#g-1101')[0].getBBox(); 


  var x = bbox.x-((bbox.width));
  var y = bbox.y-((bbox.height));
  //scale should be 1 less
  var translate = [-(x*(scale-1)),-(y*(scale-1))];

工作代码here

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2012-11-22
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2017-01-29
    • 2013-05-16
    • 2019-07-25
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多