javascript D3:获取被选元素的边界框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24534988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
D3: get the bounding box of a selected element
提问by dao hodac
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 examplebut 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. did I miss something?
我没有发现任何关于 D3 的东西。我错过了什么?
Thanks
谢谢
回答by Jay Day Zee
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 firstitem in the d3 selection:
d3 有一个函数“.node()”,它返回d3 选择中第一项的底层 DOM 节点:
d3.select("#usefulSelector").node().getBBox();
for you specifically:
专门为您:
d3.select(myElement).node().getBBox()
回答by reblace
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.
一旦你有了边界框,就需要决定你想要实际转换视图以放大到边界框的具体程度。有很多不同的方法,所以我将把它们留给你去研究。