D3.js adjust rect to text size: getBBox()?

匿名 (未验证) 提交于 2019-12-03 01:40:02

问题:

I'm creating a force directed graph using D3.js, see JSFiddle: http://jsfiddle.net/pwxecn8q/.

The text and rect are placed in the same group. When appending the rects I want to select the text element for the same group. Call getBBox() on it and use those values to resize the rect to fit the text "in" it. However, I'm unsure how to select the text element from the same group when appending the rects...

Any suggestion on how to go about this?

The relevant code:

var color = d3.scale.category20();   var svg = d3.select("body").append("svg")     .attr("width", width)     .attr("height", height);  var force = d3.layout.force()     .gravity(.05)     .distance(100)     .charge(-100)     .size([width, height]);  force.nodes(graphData.nodes)     .links(graphData.links)     .start();  var link = svg.selectAll(".link")     .data(graphData.links)     .enter().append("line")     .attr("class", "link");  var node = svg.selectAll("g.node")     .data(graphData.nodes)     .enter()     .append("g")     .attr("class", "node")     node.append("rect")     .attr("x", 0)     .attr("y", 0)     .attr("width", 10)     .attr("height", 10)     .style("fill", function (d) {     return color(d.group); })     .call(force.drag);    node.append("text")     .attr("x", 0)     .attr("y", 10)     .attr("text-anchor", "middle")     .text(function (d) {     return d.name })     force.on("tick", function () {     link.attr("x1", function (d) {         return d.source.x;     })         .attr("y1", function (d) {         return d.source.y;     })         .attr("x2", function (d) {         return d.target.x;     })         .attr("y2", function (d) {         return d.target.y;     });      node.attr("transform", function (d) {         return "translate(" + d.x + "," + d.y + ")";     });  }); 

回答1:

You can use the Bounding Box of the node (g element, which contains the text).

node.selectAll('rect')     .attr("width", function(d) {return this.parentNode.getBBox().width;}) 

Updated jsfiddle: http://jsfiddle.net/pwxecn8q/3/



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