How to place text in the middle of the svg path

For rendering SVG, I use jQuery SVG plugin. And now I want to add text to each path and polygon. On jsFiddle, you can see the generated markup by the plugin.

To create the 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 jsFiddle code , you can see that the textpath tag exists, but it does not appear. How to add text to the center of each path?
Thanks.

+6
source share
2 answers

To put text in a straight line on top of the form, in the middle of the bounding box, see:

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

It just adds some javascript to fit the text.

 function addText(p) { var t = document.createElementNS("http://www.w3.org/2000/svg", "text"); var b = p.getBBox(); t.setAttribute("transform", "translate(" + (bx + b.width/2) + " " + (by + 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 applies to path elements, but you can adjust the selector to include everything you need.

+12
source

There are several issues here.

a) SVG is case sensitive, so textPath, not text path.

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

Here jsFiddle is fixed .

+1
source

Source: https://habr.com/ru/post/917856/


All Articles