更改矩形大小以适合文本 [英] Changing size of rect to fit inside text
问题描述
我使用append('text')
将一些文本附加到具有D3.js的svg对象上.
I have some text I append to an svg object with D3.js using append('text')
.
我的代码如下:
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');
我想要的是将文本放在矩形"内部,该矩形根据我添加的文本的长度而改变大小. rect的stroke
为1px
以便呈现盒子的外观.
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.
我该怎么做?显然,宽度和高度不能设置为auto
(css属性).我在那里需要可以在D3上正常工作的其他东西.
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.
被投票否决..
推荐答案
您无法在SVG中自动执行此操作-必须计算文本的尺寸,并相应地添加矩形.幸运的是,这并不太困难.此功能说明了基本思想:
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);
}
给出一个容器和一个text
元素,计算text
元素的尺寸(必须设置文本以使其正常工作),然后将具有这些尺寸的rect
添加到容器中.如果您想稍微夸张一些,可以添加另一个参数,该参数允许您指定填充,以使文本和边框不会紧挨着.
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.
完整演示此处.
这篇关于更改矩形大小以适合文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!