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

一、简介

  • 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡尔特斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值