路径上的水平文本 [英] horizontal text on path
本文介绍了路径上的水平文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以不旋转html svg文本路径上的文本,从而使数字保持水平对齐?
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>
推荐答案
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!).
(留给读者尝试尝试更好的匹配,提示:在每个字符上使用BBox(),然后调整dy=xxx
和steps
值).
(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>
这篇关于路径上的水平文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文