Resize the rectangle to fit inside the text

I have text that I am adding 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');

      

I would like to place this text "inside" a rectangle that resizes depending on the length of the added text. The rectangle would have stroke

of 1px

to create a window view.

How can i do this? Obviously width and height cannot be set to auto

(css properties). I need something else that can work natively on D3.

Edit: confused down.

+3


source to share


1 answer


You cannot do this automatically in SVG - the dimensions of the text have to be calculated 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 the container and element text

, calculate the dimensions of the element text

(the text must be set to work properly) and add rect

to the container with those dimensions. If you want to get a little involved, you can add another argument that will allow you to specify padding so that the text and border are not immediately next to each other.

Complete the demo here .

+6


source







All Articles