D3:获取选定元素的边界框

D3: get the bounding box of a selected element

本文关键字:边界 元素 获取 D3      更新时间:2023-09-26

我在svg中有几个元素,我想放大其中一个

我想做同样的例子,但与非地理路径。就像

d3.select(myElement).bounds() that I can use to pan and zoom my svg

我没有发现任何与D3。我错过什么了吗?

谢谢

原始问题的答案,以及隐含的一般观点是,是的,D3有一个访问底层DOM节点的函数,不,它不会费心在不必要的地方覆盖那些函数:

d3有一个函数".node()",它返回d3选择中第一个项的底层DOM节点:

d3.select("#usefulSelector").node().getBBox();

:

d3.select(myElement).node().getBBox()

文档:节点https://github.com/mbostock/d3/wiki/Selections

您可以在SVG元素上调用"getBBox()"来获取SVG坐标形式的边界框。

var mousemove = function(d){
    var bbox = this.getBBox();
    ...
};
var svg = d3.select("body").append("svg")
    .attr("height", "100")
    .attr("width", "400");
var gPath = svg.append("g");

gPath.append("path")
    .attr("d", "M 250 10 L 320 10 L 350 50 L 290 65 z")
    .attr("fill", "steelblue")
    .on("mousemove", mousemove);

一旦你有了边界框,它的问题是决定如何具体地转换视图缩放到边界框。有很多不同的方法,所以我把它留给你们去研究。

这是一个jsFiddle: http://jsfiddle.net/reblace/3rDPC/3/

如果你正在使用SVG元素(例如<text>),你可以使用element.node().getBBox(),否则.getBBox()将无法工作。对于普通的html元素使用element.node().getBoundingClientRect()

console.log(d3.select('text').node().getBBox())
console.log(d3.select('div').node().getBoundingClientRect())
.el {
  margin: 30px;
  width: 150px;
  height: 50px;
  background: red;
}
<script src="https://d3js.org/d3.v6.min.js"></script>
<div class="el"></div>
<svg><text>Text</text></svg>