Horizontal Text On Path
Is there a way to not rotate text on a html svg textpath, so that the digits stay horizontally aligned?
Solution 1:
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 lengthvar steps = len/t_text.length; // get width of stepvar start_pt = 0; // start at beginningvar prev_pt = curve.getPointAtLength(0); // measure first step
t.textContent = ""; // clear up original text;for (var i = 0; i < t_text.length; ++i) { // char loopvar new_pt = curve.getPointAtLength(start_pt); // measure ptvar 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
}
functiongenTspan(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;
}
<svgid="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><pathid="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><useid="curve"xlink:href="#MyPath"fill="none"stroke="red" /><textx="90"y="200"id="origText"font-family="Verdana"font-size="36">We go up, then we go down, then up again</text></svg>
Post a Comment for "Horizontal Text On Path"