Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 267
user1260827 Avatar asked Jun 12 '12 08:06

user1260827


People also ask

How do I center an SVG path?

You can change the svg viewBox attribute to center the path. This is especially useful if you have several paths in the svg, so you do not have to add a transform to each one. In your example that would be viewBox="0 15.674 144 144" , getting the y-offset the same way as in Pauls answer.


2 Answers

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.

like image 154
Erik Dahlström Avatar answered Sep 20 '22 02:09

Erik Dahlström


There are a couple of issues here.

a) SVG is case sensitive so it's textPath and not textpath.

b) textPath has to be enclosed in a <text> element to be valid

Here's your jsFiddle fixed up.

like image 21
Robert Longson Avatar answered Sep 21 '22 02:09

Robert Longson