Using D3 I display a bunch of circles in different sizes, each filled with text. I'm stuck with finding the correct font size so that the text fits correct in the circle, depending of it's size and the length of the text. Long text should possibly be broken up in more lines. Here is my code:
var data = {
"name": "",
"children": [
{ "name": "This is a tag", "value": 242 },
{ "name": "Circle", "value": 162 },
{ "name": "Tree", "value": 80 },
{ "name": "My sentence is very long and needs breaks", "value": 80 },
]
}
var diameter = 300,
format = d3.format(",d");
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var svg = d3.select("body").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
d3.json(data, function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(data)
.filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { return '#f88' });
// text part
node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.style("font-size", function(d) { return Math.round(d.r/3)+'px'; })
.text(function(d) { return d.name.substring(0, d.r / 3); });
});
d3.select(self.frameElement).style("height", diameter + "px");
I have created a fiddle as well on http://jsfiddle.net/L4nMx/ I think I should calculate the width of the text and modify the font size until it matches the circle's size or something like that. Or is there any "strech" function to do this the easy way?
foreignObject
which is not supported by IE...what do you think? – Piatt