Lars Kotthof has a good explanation here of how to create SVG elements that correspond to size of text. However, I'm looking to do this dynamically with data pulled from JSON or CSV.
svg.selectAll('rect')
.data(states.features)
.enter()
.append('rect')
.attrs({
x: function(d) { return path.centroid(d)[0] - 50; },
y: function(d) { return path.centroid(d)[1] - 13; },
'text-anchor': 'middle',
'width': 100,
'height': 18,
'fill': 'rgba(232, 232, 232, 0.8)',
'opacity': 1,
'rx': 7,
'ry': 7
});
svg.selectAll('text')
.data(states.features)
.enter()
.append('text')
.text(function(d) { return d.properties.name; })
.attrs({
x: function(d) { return path.centroid(d)[0]; },
y: function(d) { return path.centroid(d)[1]; },
'text-anchor': 'middle',
'font-size': '7pt',
'fill': 'rgb(25,25,25)',
'opacity': 1
});
The concept I'm not grasping is how I can write a function, similar to Lars's, that creates both the <rect>
and the <text>
and uses the dimensions of the text to determine the dimensions of the rectangle.