Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 stateTexts = svg.append('rect')
            .attr('x', xstateText)
            .attr('y', ystateText)
            .attr('width', 'auto')
            .attr('height', 'auto')

var stateText = svg.append('text')  
            .attr('x', xstateText)
            .attr('y', ystateText)  
            .style("font-family", "Arial")
            .style("font-size", "14px")
            .style("font-weight", 'bold');

What I'd like is to put that text "inside" a rect which changes size based on the length of the text I append. The rect would have a stroke of 1px so as to give the appearance of a box.

How can I accomplish this? Obviously, width and height can't be set to auto (css properties). I need something else there that can work native to D3.

Edit: Confused by the downvote..

like image 708
Union find Avatar asked Dec 26 '22 05:12

Union find


1 Answers

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:

function mkBox(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.

like image 126
Lars Kotthoff Avatar answered Jan 02 '23 08:01

Lars Kotthoff