详细介绍SVG的text文本元素,包括文本定位、多行文本和文本属性设置。通过实例掌握SVG文本绑制的基础技巧。 text元素是SVG中最基础的文本绑制元素,用于在指定位置显示文字内容。
<text x="X坐标" y="Y坐标">文本内容</text>
x和y属性确定文本的位置,其中y坐标对应文本的基线位置。
<line x1="30" y1="50" x2="270" y2="50" stroke="#e74c3c" stroke-width="1" stroke-dasharray="5,5"/>
<text x="30" y="50" font-size="20" fill="#3498db">基线位置</text>
<circle cx="30" cy="50" r="3" fill="#e74c3c"/>
x和y属性可以接受多个值,分别对应每个字符的位置。
<text x="30 60 90 120 150 180 210 240" y="50" font-size="24" fill="#3498db">ABCDEFGH</text>
dx和dy属性用于设置文本的相对偏移量。
<text x="30" y="50" font-size="18" fill="#666">正常文本</text>
<text x="30" y="80" dx="20" font-size="18" fill="#3498db">dx偏移20</text>
<text x="30" y="110" dy="10" font-size="18" fill="#e74c3c">dy偏移10</text>
<text x="30" y="140" dx="10" dy="5" font-size="18" fill="#2ecc71">dx和dy组合</text>
rotate属性可以旋转文本或单个字符。
<text x="50" y="70" rotate="45" font-size="20" fill="#3498db">旋转45度</text>
<text x="150" y="70" rotate="0 15 30 45 60 75 90" font-size="24" fill="#e74c3c">ABCDEFG</text>
textLength属性可以强制设置文本的显示长度,lengthAdjust控制调整方式。
<text x="30" y="40" font-size="16" fill="#666">原始文本</text>
<text x="30" y="70" textLength="200" font-size="16" fill="#3498db">拉伸到200px</text>
<text x="30" y="100" textLength="100" font-size="16" fill="#2ecc71">压缩到100px</text>
<text x="30" y="130" textLength="200" lengthAdjust="spacing" font-size="16" fill="#f39c12">仅调整间距</text>
| 属性 | 说明 | 示例 |
|---|---|---|
| x | X坐标 | x="100" |
| y | Y坐标(基线) | y="50" |
| dx | X偏移 | dx="10" |
| dy | Y偏移 | dy="5" |
| rotate | 旋转角度 | rotate="45" |
| textLength | 文本长度 | textLength="200" |
| lengthAdjust | 长度调整方式 | lengthAdjust="spacing" |
<rect x="30" y="100" width="40" height="30" fill="#3498db"/>
<text x="50" y="95" text-anchor="middle" font-size="12" fill="#333">25</text>
<rect x="80" y="70" width="40" height="60" fill="#e74c3c"/>
<text x="100" y="65" text-anchor="middle" font-size="12" fill="#333">50</text>
<rect x="130" y="40" width="40" height="90" fill="#2ecc71"/>
<text x="150" y="35" text-anchor="middle" font-size="12" fill="#333">75</text>
<rect x="180" y="20" width="40" height="110" fill="#f39c12"/>
<text x="200" y="15" text-anchor="middle" font-size="12" fill="#333">90</text>
<line x1="50" y1="20" x2="50" y2="120" stroke="#333" stroke-width="2"/>
<line x1="50" y1="120" x2="280" y2="120" stroke="#333" stroke-width="2"/>
<text x="30" y="30" font-size="10" fill="#666">100</text>
<text x="30" y="60" font-size="10" fill="#666">75</text>
<text x="30" y="90" font-size="10" fill="#666">50</text>
<text x="30" y="120" font-size="10" fill="#666">25</text>
<text x="80" y="135" text-anchor="middle" font-size="10" fill="#666">一月</text>
<text x="130" y="135" text-anchor="middle" font-size="10" fill="#666">二月</text>
<text x="180" y="135" text-anchor="middle" font-size="10" fill="#666">三月</text>
<text x="230" y="135" text-anchor="middle" font-size="10" fill="#666">四月</text>