I am using d3.js visualization for depicting nodes. I am getting the text as of now. I have a code to resize the width of the rect depending on the length of text going into it. But, sometimes it is not working, the text is going out of the rect box. Here is the code for that.
nodeEnter.append("rect").attr("x",
function(d) {
var x = d.name.length;
x = x + 150;
return -(x) / 2;
}).attr("y", -10).attr(
"width",
function(d) {
var x = d.name.length;
x = x + 150;
return x;
}).attr("height", 20).style({
"fill": function(d) {
return d._children ? "lightsteelblue" : "#fff";
},
"stroke": "steelblue",
"stroke-width": "1.5px"
});
nodeEnter.append("text").attr("x", 0).attr("y", 0)
.attr("dy", ".35em").attr(
"text",
function(d) {
return d.children || d._children ? "end" : "start";
}).text(function(d) {
return d.name;
}).style({
"fill-opacity": 1e-6,
"font-size": "10px",
"font-family": "sans-serif"
}).attr(
"text-anchor", "start");
Here I took the length of the text to go into the box and added 150. But, not working beyond a point. Can I get any help here ?
As per the suggestion of using getBBox(). I tried using it and here is the edited code
var text = nodeEnter.append("svg:text").attr("x", 0).attr("y", 0)
.attr("dy", ".35em").attr(
"text",
function(d) {
return d.children || d._children ? "end" : "start";
}).text(function(d) {
return d.name;
}).style({
"fill-opacity": 1e-6,
"font-size": "10px",
"font-family": "sans-serif"
}).attr(
"text-anchor", "middle");
var bbox = text.node().getBBox();
nodeEnter.append("rect").attr("x",
function(d) {
var x = d.name.length;
x = x + 150;
return -(x) / 2;
}).attr("y", -10).attr(
"width", bbox.width).attr("height", bbox.height)
.style({
"fill": function(d) {
return d._children ? "lightsteelblue" : "#fff";
},
"stroke": "steelblue",
"stroke-width": "1.5px"
});
This is making the text inside the rectangle box disappear and only the overflown text is visible