admin 管理员组文章数量: 1086019
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 acplish 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..
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 acplish 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..
Share Improve this question edited Aug 10, 2014 at 0:45 Union find asked Aug 10, 2014 at 0:40 Union findUnion find 8,18017 gold badges68 silver badges117 bronze badges1 Answer
Reset to default 10You can't do this automatically in SVG -- the dimensions of the text have to be puted 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, pute 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.
本文标签: javascriptChanging size of rect to fit inside textStack Overflow
版权声明:本文标题:javascript - Changing size of rect to fit inside text - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744036428a2522448.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论