Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

jquery - How to place text in the center of an svg path

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'));

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To place text in a straight line on top of a shape, in the middle of the boundingbox see:

http://jsfiddle.net/dYuAA/114/

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...