[英]D3: get the bounding box of a selected element
I have several elements in a svg and I want to zoom on one of them.我在 svg 中有几个元素,我想放大其中一个。
I'd like to do the same as this example but with non geo paths.我想做与此示例相同的操作,但使用非地理路径。 Something like就像是
d3.select(myElement).bounds() that I can use to pan and zoom my svg
I did not find anything with D3.我没有发现任何关于 D3 的东西。 did I miss something?我错过了什么?
Thanks谢谢
The Answer to the original question, and the implied general point is that yes, D3 has a function to access the underlying DOM node, and that no, it doesnt bother to override those functions where not necessary:原始问题的答案以及隐含的一般观点是,是的,D3 具有访问底层 DOM 节点的功能,并且不,它不会在不必要的情况下覆盖这些功能:
d3 has a function ".node()" which returns the the underlying DOM node of the first item in the d3 selection: d3 有一个函数“.node()”,它返回 d3 选择中第一项的底层 DOM 节点:
d3.select("#usefulSelector").node().getBBox();
for you specifically:专门为您:
d3.select(myElement).node().getBBox()
docs: https://github.com/mbostock/d3/wiki/Selections#node文档: https : //github.com/mbostock/d3/wiki/Selections#node
You can call "getBBox()" on SVG elements to get their bounding box in terms of SVG coordinates.您可以在 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);
Once you have the bounding box, its a matter of deciding how specifically you want to actually transform the view to zoom into the bounding box.一旦你有了边界框,就需要决定你想要实际转换视图以放大到边界框的具体程度。 There are a bunch of different approaches so I'll leave that for you to investigate.有很多不同的方法,所以我将把它留给你去研究。
If yo're usign an SVG element (eg <text>
), you can use element.node().getBBox()
otherwise .getBBox()
will not work.如果您使用 SVG 元素(例如<text>
),您可以使用element.node().getBBox()
否则.getBBox()
将不起作用。 Use element.node().getBoundingClientRect()
for normal html elements.对普通 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.