How to place text in the center of an svg path

喜欢而已 提交于 2019-11-29 04:27:55

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!