SVG 文本(一)text、tspan 的基本使用

2,754 阅读1分钟

一、简介

  • SVG 通过 <text><tspan> 创建文本,支持 <a> 插入超链接,可以通过 <textPath> 让文本在指定的路径上排列。

  • <text><tspan> 基本属性:

    • x、y:定位标准

    • dx、dy:字形偏移

    • style:设置样式

二、text

  • 案例

    <svg xmlns="http://www.w3.org/2000/svg" width="600" height="400">
        <defs>
          <!-- 网格 -->
          <pattern id="grid" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
            <path fill="none" stroke="#f1f1f1" d="M 0 0 H 20 V 20"/>
          </pattern>
        </defs>
        <!-- 设置网格 -->
        <rect width="600" height="400" fill="url(#grid)"/>
        <!-- 小格子内容 -->
        <text x="20" y="20">文本测试</text>
        <!-- 基线对齐效果 -->
        <path d="M 100 0 V 300 M 0 100 H 400 M 0 200 H 400 M 0 300 H 400" stroke="red"/>
        <text x="100" y="100" style="font-size: 50px;">DZM 文本测试</text>
        <!-- dx dy 测试 -->
        <text x="100" y="200" style="font-size: 50px;" dx="10" dy="10">DZM 文本测试</text>
        <text x="100" y="300" style="font-size: 50px;" dx="20 40 60 80" dy="20 20 20 20 20">ABCDEFG</text>
    </svg>
    

    image.png

  • JS 动态赋值文本

三、tspan

  • tspan 标签支持单独配置 dx dy,优先使用自身自带的,后续文字如果没有单独配置,会自动继承上一个文字的 dx dy

    <svg xmlns="http://www.w3.org/2000/svg" width="600" height="400">
        <defs>
          <!-- 网格 -->
          <pattern id="grid" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
            <path fill="none" stroke="#f1f1f1" d="M 0 0 H 20 V 20"/>
          </pattern>
        </defs>
        <!-- 绘制网格 -->
        <rect width="600" height="400" fill="url(#grid)"/>
        <!-- 基线对齐效果 -->
        <path d="M 100 0 V 300 M 0 100 H 400 M 0 200 H 400 M 0 300 H 400" stroke="red"/>
        <text x="100" y="100" style="font-size: 50px;">
          <tspan fill="red">AB</tspan>
          <tspan stroke="blue" stroke-width="2" fill="red">CDE</tspan>
          <tspan fill="blue">FG</tspan>
        </text>
        <!-- 测试 dx dy 在 tspan 身上的效果 -->
        <text x="100" y="200" style="font-size: 50px;">
          <tspan fill="red" dy="-20">AB</tspan>
          <tspan stroke="blue" stroke-width="2" fill="red" dy="20 -10">CDE</tspan>
          <tspan fill="blue">FG</tspan>
        </text>
        <!-- 测试 dx dy 在 tspan 身上的效果 -->
        <text x="100" y="300" dy="30" style="font-size: 50px;">
          <tspan fill="red">AB</tspan>
          <tspan stroke="blue" stroke-width="2" fill="red" dy="20 -10">CDE</tspan>
          <tspan fill="blue">FG</tspan>
        </text>
    </svg>
    

    image.png