醉美水芙蓉 发表于 2026-7-18 21:25:01

马黑黑《SVG:在textPath中实现文本两端对齐》

<style>
    @import 'https://638183.freep.cn/638183/web/css/hl.css';
    .artBox { margin: 20px auto; font: normal 18px/26px sans-serif; }
    .artBox mark { padding: 2px 6px; background: #ccc; }
    .artBox blockquote { padding: 14px; border: solid gray; border-width: 0 4px; border-radius: 10px; background: #ddd; }
    .artBox p { margin: 10px 0; }
    .tMid { text-align: center; }
    #svgCode { font-size: 16px; white-space: pre-wrap; }
</style>

<div class="artBox">
    <p><mark>&lt;textPath&gt;</mark> 元素允许文字沿着路径绘制,提供了灵活的文本布局方式。通过将 <mark>&lt;textPath&gt;</mark> 与 <mark>&lt;path&gt;</mark> 结合,可以实现文字沿曲线、折线或复杂路径的展示。需要注意的是:其一,textPath 的书写,P 要大写;其二,textPath 应作为 <mark>&lt;text&gt;</mark> 的子元素出现;其三,textPath 内可以使用 <mark>&lt;tspan&gt;</mark> 子文本以便精细修饰碎片化的文本样式。</p>
    <p>以下是一个完整的 textPath 示例:</p>
    <p id="showSvg" class="tMid"></p>
    <p>代码:</p>
    <pre id="svgCode" class="hlCode">&lt;svg width="400" height="200" style="border: 1px solid gray"&gt;
    &lt;path id="path1" d="M20 20Q200 350,380 20" fill="none" stroke="tan" /&gt;
    &lt;text fill="steelblue" style="font: bold 26px sans-serif"&gt;
      &lt;textPath
            id="myTPath"
            href="#path1"
            lengthAjust="spacing"
            textLength="510"&gt;
                山长水阔知何处
      &lt;/textPath&gt;
    &lt;/text&gt;
&lt;/svg&gt;</pre>
    <p>textPath 元素里两个属性 <mark>lengthAdjust</mark> 和 <mark>textLength</mark> 的设置是文本在路径上两端对齐的关键:</p>
    <blockquote>textPath :文本拉伸形式,控制文本如何拉伸到 textLength 属性定义的长度,值有 spacing(默认,字母或汉字之间的空格可能会增大或缩小)和 spacingAndGlyphs(整个文本元素被拉伸到文本的方向)<br>textLength :文本长度,定义文本在指定路径中的布局长度(但使用百分比时是以 SVG viewBox的宽度为参照)。</blockquote>
    <p>文本长度(textLength)一般与路径长度一致,路径长度可以使用 JS 的<code class="hlCode">path.getTotalLength()</code>方法获取。考虑到路径可能会随手改动,可以在 JS 中为 textPath 的 textLength 属性动态赋值,这样在 HTML 代码中的赋值可以略为随意:</p>
    <pre class="hlCode">myTPath.setAttribute('textLength', path1.getTotalLength());</pre>
    <p>另外,如果需要隐藏路径,可以将路径置入 <mark>&lt;defs&gt;</mark> 标签内,像这样:</p>
    <pre class="hlCode">&lt;defs&gt;
    &lt;path id="path1" d="M20 20Q200 350,380 20" /&gt;
&lt;/defs&gt;</pre>
    <p>【小结】实现文本路径上的文本两端分散对齐,核心在于配套使用两个属性,<mark>lengthAjust="spacing"</mark> 和 <mark>textLength="长度"</mark>,其中文本长度和文本所安置的路径的长度应保持大致一致。</p>
</div>

<script>
    showSvg.innerHTML = svgCode.textContent;
</script>

klxf 发表于 2026-7-19 14:07:29

实用的知识与方法,谢谢分享
页: [1]
查看完整版本: 马黑黑《SVG:在textPath中实现文本两端对齐》