Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG: right-align text at the end of a textPath

Tags:

html

svg

I'd like to right-lign text at the end of a 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>

You can see this working here: http://jsfiddle.net/7sqdxw11/

The Start text begins right where I'd expect - at the beginning of the textPath.

However, the end text ends well short of the end of the textPath.

(The Middle is also well shy of the middle of the textPath).

Here's a screenshot:

enter image description here

What am I doing wrong? How to I get the End to end at the right end of the textPath arc?

like image 652
mattstuehler Avatar asked Sep 26 '22 13:09

mattstuehler


1 Answers

In SVG percentage coordinates generally refer to the either the width of the SVG, or in some cases the width of the parent object.

So in your example the "100%" will result in a value of 400px - the width of your SVG. However your path actually has a length of 466. You can get the length by experimentation, or by using some Javascript:

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

So if you change the "100%" to "466" you get the effect you wanted.

<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>
like image 177
Paul LeBeau Avatar answered Nov 15 '22 10:11

Paul LeBeau