路径上的水平文本

时间:2016-04-10 20:51:03

标签: html svg text

有没有办法不在html svg文本路径上旋转文本,以便数字保持水平对齐?

<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.

1 个答案:

答案 0 :(得分:1)

使用此mozilla source作为模板,这是我的示例。不是100%匹配曲线,因为每个字符宽度都不固定,而我的编码则不然。我的头脑里有这个代码3年了(是的,不开玩笑!)。

(留给读者尝试获得更好的匹配,提示:对每个字符使用BBox(),然后调整dy=xxxsteps值。

&#13;
&#13;
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;

}
&#13;
<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>
&#13;
&#13;
&#13;