SVG:如何将文本右对齐到textPath的末尾

6

我想把文本右对齐到textPath的末尾:

<svg height="300" width="400">
    <defs>
        <path id="myTextPath" d="M30,160  A175,175 0 0,1 370,160" />
    </defs>
    <path d="M30,160  A175,175 0 0,1 370,160" style="stroke: black; stroke-width:1; fill:none;" />
    <g fill="black" stroke="none">
        <text x="0%" y="0" text-anchor="start">
            <textPath xlink:href="#myTextPath">Start</textPath>
        </text>
        <text x="50%" y="0" text-anchor="middle">
            <textPath xlink:href="#myTextPath">Middle</textPath>
        </text>
        <text x="100%" y="0" text-anchor="end">
            <textPath xlink:href="#myTextPath">End</textPath>
        </text>
    </g>
</svg>

您可以在此处查看其工作示例:http://jsfiddle.net/7sqdxw11/ “开始”文本从textPath的开头开始,这一点我很满意。
然而,“结束”文本却远未到达textPath的末端。
(“中间”文本也明显偏离了textPath的中央)。
以下是屏幕截图: enter image description here 我做错了什么?如何使“结束”文本位于textPath弧的正确末端?
2个回答

4

在SVG中,百分比坐标通常是指SVG的宽度,或者在某些情况下是指父对象的宽度。

因此,在您的示例中,“100%”将导致值为400px-您的SVG的宽度。但是,您的路径实际上长度为466。您可以通过试验获得长度,也可以使用一些Javascript:

var len = document.getElementById("myTextPath").getTotalLength();

所以,如果您将“100%”更改为“466”,您就会得到您想要的效果。

<svg height="300" width="400">
    <defs>
        <path id="myTextPath" d="M30,160  A175,175 0 0,1 370,160" />
    </defs>
    <path d="M30,160  A175,175 0 0,1 370,160" style="stroke: black; stroke-width:1; fill:none;" />
    <g fill="black" stroke="none">
        <text x="0" y="0" text-anchor="start">
            <textPath xlink:href="#myTextPath">Start</textPath>
        </text>
        <text x="233" y="0" text-anchor="middle">
            <textPath xlink:href="#myTextPath">Middle</textPath>
        </text>
        <text x="466" y="0" text-anchor="end">
            <textPath xlink:href="#myTextPath">End</textPath>
        </text>
    </g>
</svg>


1
不要使用<text x="...属性。而是在<textPath>上使用startOffset(以及text-anchor)代替:

<svg height="300" width="400">
    <defs>
        <path id="myTextPath" d="M30,160  A175,175 0 0,1 370,160" />
    </defs>
    <path d="M30,160  A175,175 0 0,1 370,160" style="stroke: black; stroke-width:1; fill:none;" />
    <g fill="black" stroke="none">
        <text>
            <textPath xlink:href="#myTextPath">Start</textPath>
        </text>
        <text>
            <textPath xlink:href="#myTextPath" startOffset="50%" text-anchor="middle">Middle</textPath>
        </text>
        <text>
            <textPath xlink:href="#myTextPath" startOffset="100%" text-anchor="end">End</textPath>
        </text>
    </g>
</svg>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接