【问题标题】:Zoom to bounding box of path on externally loaded svg using D3使用 D3 缩放到外部加载的 svg 上的路径边界框
【发布时间】:2020-02-23 22:13:51
【问题描述】:

我正在使用 D3 加载不使用 topojson 的外部 SVG 地图(因为地图是手工创建的,不是传统地图)。我试图定位元素#lines path,以便单击时,每个路径都会缩放并填充其边界框。

我正在尝试使用 Mike Bostock 的 this example,但不知道如何使用未使用 topojson 的数据复制它。看到这一行:

.data(topojson.feature(us, us.objects.states).features)

这甚至可能吗?

这是我用来加载 SVG 的代码。

var mapContainer = $('.map');

d3.xml("../assets/subwaymap.svg", function(error, subwayMap) {
  if (error) throw error;
  $('.map').append(subwayMap.documentElement)

我尝试使用.getBBOX 获取边界框,但对它的连接方式感到困惑。似乎我见过的所有示例都使用d3.create("svg"),然后添加其中的所有功能,但由于我的数据已经附加到 DOM,这是否有必要? D3相当新。谢谢!

【问题讨论】:

标签: javascript d3.js svg


【解决方案1】:

两个初步考虑:d3.create("svg") 在真正的 D3 代码中很少使用。此外,您没有将数据附加到 DOM,只是您加载的 SVG 元素(除非您将其称为 "data")。

回到你的问题,你不需要path.bounds 来使你的代码工作,实际上你甚至不需要d3.zoom。您只需要获取元素的框(带有getBBox)并进行适当的转换。

不过,真正的问题是您需要将所有元素包装在 <g> 中,因为您无法将转换应用于 SVG 1.1 中的根 SVG(显然这在 SVG 2 中是可能的)。

这是一个基本的演示。在这个演示中,我使用了一个由不同元素(圆形、矩形、文本...)制成的外部 SVG,它代表了您要附加的 SVG。你会得到这个 SVG:

const svg = d3.select("svg");

然后,考虑到你设法解决了我提到的<g> 问题,你得到了那个组......

const g = svg.select("g");

...然后您选择要放大的元素(此处为所有内容),绑定事件侦听器:

const elements = g.selectAll("*")
    .on("click", clicked);

在这个演示中,我使用 Bostock 的数学来节省(我的)时间,但您可以更改它。点击元素放大,再次点击缩小。

const width = 500,
  height = 400;
const svg = d3.select("svg");
const g = svg.select("g");
const elements = g.selectAll("*")
  .each(function() {
    d3.select(this).datum({})
  })
  .on("click", clicked);

function clicked(d) {
  d.clicked = !d.clicked;
  const bounds = this.getBBox();
  const x0 = bounds.x;
  const x1 = bounds.x + bounds.width;
  const y0 = bounds.y;
  const y1 = bounds.y + bounds.height;
  g.transition().duration(1000).attr("transform", d.clicked ? "translate(" + (width / 2) + "," + (height / 2) + ") scale(" + (1 / Math.max((x1 - x0) / width, (y1 - y0) / height)) + ") translate(" + (-(x0 + x1) / 2) + "," + (-(y0 + y1) / 2) + ")" : "transform(0,0) scale(1)");
}
<svg width="500" height="400">
<g>
<circle cx="50" cy="50" r="30" stroke="black" stroke-width="3" fill="teal"></circle>
<rect x="300" y="20" rx="20" ry="20" width="150" height="150" style="fill:tomato;stroke:black;stroke-width:3"/>
<polygon points="200,100 250,190 160,210" style="fill:lavender;stroke:purple;stroke-width:3" />
<path d="M 140 350 q 150 -200 350 0" stroke="blue" stroke-width="5" fill="none" />
<text x="30" y="300" transform="rotate(-30, 30, 300)">Foo Bar Baz</text>
</g>
</svg>
<script src="https://d3js.org/d3.v5.min.js"></script>

【讨论】:

  • 非常感谢!所有这些都非常有帮助,我从查找您建议的内容中学到了很多东西。
猜你喜欢
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多