如何将文本放置在svg路径的中心 [英] How to place text in the center of an svg path
问题描述
为了渲染SVG,我使用了jQuery SVG插件.而且,现在我想向每个路径和多边形添加文本.在 jsFiddle 上,您可以看到插件生成的标记.
For rendering SVG I'm using jQuery SVG plugin. And, now I want to add text to each path and polygon. On jsFiddle you can see generated markup by plugin.
为了创建文本,我编写了以下代码:
For creating text I wrote the following code:
var svgg = $("#rsr").svg('get');
var texts = svgg.createText();
svgg.textpath($("#Layer_x0020_1"),id, texts.string('We go ').
span('up', { dy: -30, fill: 'red' }).span(',', { dy: 30 }).
string(' then we go down, then up again'));
在 jsFiddle 上的代码中,您可以看到textpath
标记存在,但是它不可见.
如何在每个路径的中心添加文本?
谢谢.
In the code on jsFiddle you can see that the textpath
tag exists, but it's not visible.
How to add text to the center of each path?
Thanks.
推荐答案
要将文本以直线形式放置在形状顶部,请在边界框的中间,参见:
To place text in a straight line on top of a shape, in the middle of the boundingbox see:
http://jsfiddle.net/dYuAA/114/
它只是添加了一些JavaScript来放置文本.
It just adds some javascript to place text.
function addText(p)
{
var t = document.createElementNS("http://www.w3.org/2000/svg", "text");
var b = p.getBBox();
t.setAttribute("transform", "translate(" + (b.x + b.width/2) + " " + (b.y + b.height/2) + ")");
t.textContent = "a";
t.setAttribute("fill", "red");
t.setAttribute("font-size", "14");
p.parentNode.insertBefore(t, p.nextSibling);
}
var paths = document.querySelectorAll("path");
for (var p in paths)
{
addText(paths[p])
}
以上仅查看路径元素,但您可以调整选择器以包括所需的内容.
The above only looks at path elements, but you could tweak the selector to include whatever you need.
这篇关于如何将文本放置在svg路径的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!