Skip to content Skip to sidebar Skip to footer

Changing Size Of Rect To Fit Inside Text

I have some text I append to an svg object with D3.js using append('text'). My code looks like this: var countries = svg.append('svg:g') .attr('id', 'countries'); var stat

Solution 1:

You can't do this automatically in SVG -- the dimensions of the text have to be computed and the rectangle added accordingly. Fortunately, this is not too difficult. The basic idea is illustrated in this function:

functionmkBox(g, text) {
  var dim = text.node().getBBox();
  g.insert("rect", "text")
    .attr("x", dim.x)
    .attr("y", dim.y)
    .attr("width", dim.width)
    .attr("height", dim.height);
}

Given a container and a text element, compute the dimensions of the text element (the text must be set for this to work correctly) and add a rect to the container with those dimensions. If you want to get a bit fancier, you could add another argument that allows you to specify padding so that the text and the border are not immediately next to each other.

Complete demo here.

Post a Comment for "Changing Size Of Rect To Fit Inside Text"