julian
julian

Reputation: 11

horizontal text on path

Is there a way to not rotate text on a html svg textpath, so that the digits stay horizontally aligned?

<svg>
    <path id="line" d="..." fill="none" />
    <text>
        <textPath id="ptext" xlink:href="#lineAB" startOffset="0">
        </textPath>
    </text>
</svg>

Click here for an image to show what I mean.

Upvotes: 1

Views: 621

Answers (1)

Alvin K.
Alvin K.

Reputation: 4379

Using this mozilla source as template, here's my example. Not 100% matching the curve since each character width is not fixed while my coding assumes otherwise. Had this code in my head for 3 years (ya, no kidding!).

(Leave it to readers to try getting a better match, hint: use BBox() on each char, then adjust the dy=xxx and steps value).

var t = document.getElementById('origText');
var t_text = t.textContent; // "We go up...."
var curve = document.getElementById("MyPath");
var len = curve.getTotalLength(); // curve length

var steps = len/t_text.length; // get width of step
var start_pt = 0; // start at beginning
var prev_pt = curve.getPointAtLength(0); // measure first step


t.textContent = ""; // clear up original text;

for (var i = 0; i < t_text.length; ++i) { // char loop
  var new_pt = curve.getPointAtLength(start_pt); // measure pt
  var ts = genTspan(t_text[i], prev_pt, new_pt); // tspan
  t.appendChild(ts); // add to <text>

  start_pt += steps; // go to next step (point)
  prev_pt = new_pt; // remember previous point
}

function genTspan(myChar,prev_pt,new_pt) {
  var tspan = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
  tspan.setAttributeNS(null, 'dy', new_pt.y - prev_pt.y); 
  tspan.textContent = myChar;
  return tspan;

}
<svg id="mySVG" width="450" height="200" viewBox="0 0 900 400"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <path id="MyPath"
          d="M 100 200
             C 200 100 300   0 400 100
             C 500 200 600 300 700 200
             C 800 100 900 100 900 100" />
  </defs>

  <use id="curve" xlink:href="#MyPath" fill="none" stroke="red"  />

  <text x="90" y="200" id="origText" font-family="Verdana" font-size="36">We go up, then we go down, then up again</text>

</svg>

Upvotes: 3

Related Questions