我有如下矩形:
<rect x="0px" y="0px" width="60px" height="20px"/>
我想把"虚构"这个词放在中间。对于其他矩形,SVG换行是否保持在其中?我似乎找不到任何关于在水平和垂直居中的形状和换行中插入文本的具体内容。此外,文本不能离开矩形。
查看https://www.w3.org/TR/SVG/text.html#TextElement示例并没有帮助,因为文本元素的x和y与矩形的x和y不同。文本元素似乎没有宽度和高度。我不确定这里的数学。
(我的HTML表就是不能工作。)
For horizontal and vertical alignment of text in graphics,
you might want to use the following CSS styles.
In particular, note that dominant-baseline:middle is probably wrong,
since this is (usually) half way between the top and the baseline,
rather than half way between the top and the bottom.
Also, some some sources (e.g. Mozilla) use dominant-baseline:hanging instead of
dominant-baseline:text-before-edge. This is also probably wrong, since
hanging is designed for Indic scripts.
Of course, if you're using a mixture of Latin, Indic, ideographs
or whatever, you'll probably need to read the documentation.
/* Horizontal alignment */
text.goesleft{text-anchor:end}
text.equalleftright{text-anchor:middle}
text.goesright{text-anchor:start}
/* Vertical alignment */
text.goesup{dominant-baseline:text-after-edge}
text.equalupdown{dominant-baseline:central}
text.goesdown{dominant-baseline:text-before-edge}
text.ruledpaper{dominant-baseline:alphabetic}
编辑:我刚刚注意到Mozilla也使用了支配基线:基线,这是绝对错误的:它甚至不是一个公认的值!我假设它默认的字体是字母,所以他们很幸运。
更多编辑:Safari(11.1.2)理解边前文本,但不理解边后文本。它在表意文字方面也失败了。好东西,苹果。因此,您最终可能不得不使用字母并允许降序。对不起。
在矩形中插入文本的一种方法是插入一个外部对象,它是一个DIV,在矩形对象中。
这样,文本将遵守DIV的限制。
var g = d3.select("svg");
g.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width","100%")
.attr("height","100%")
.attr("fill","#000");
var fo = g.append("foreignObject")
.attr("width","100%");
fo.append("xhtml:div")
.attr("style","width:80%;color:#FFF;margin-right: auto;margin-left: auto;margin-top:40px")
.text("Mussum Ipsum, cacilds vidis litro abertis Mussum Ipsum, cacilds vidis litro abertis Mussum Ipsum, cacilds vidis litro abertis");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.js"></script>
<svg width="200" height="200"></svg>