D3: get the bounding box of a selected element

时光怂恿深爱的人放手 提交于 2019-12-04 12:14:27

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 has a function ".node()" which returns the the underlying DOM node of the first item in the d3 selection:

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

for you specifically:

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

docs: 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.

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.

Here's a jsFiddle: http://jsfiddle.net/reblace/3rDPC/3/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!