H5Skills icon indicating copy to clipboard operation
H5Skills copied to clipboard

SVG 文本路径居中

Open leeenx opened this issue 7 years ago • 0 comments

路径文本

svg 中可以控制文本沿指定路径显示,只需要 <textPath> 标签就可以完成。以下是一个实例:

<svg viewBox="0,0,332,48">
  <path id="textPath" d="m0.749997,39.860256c92.99817,20.99958 250.99507,-15.99969 327.99356,1.99996" opacity="0.5" stroke-opacity="null" stroke-width="1" stroke=“#000" fill="none"/>
  <text fill="#fff" font-size="28" x="0" y="0">
    <textPath xlink:href="#textPath">
      利益点利益点利益点
    </textPath>
  </text>
</svg>

路径文本居中

有时候,我们需要将文本沿着svg中心点居中。 标签的属性如下:

属性名称 属性说明
x 起始点 x 轴的座标
y 起始点 y 轴的座标
dx 座标的 x 轴偏移位置
dy 座标的 y 轴偏移位置
rotate 旋转偏移的角度
textLength 元素的长度,这会影响输出的宽度
transform 文字的变形效果,类似 css 中的 transform

可以使用 x,dx 来定位中心点。但是,却会发现这样做不是文本居中,而是文本从中间开始:

<svg viewBox="0,0,332,48">
  <path id="textPath" d="m0.749997,39.860256c92.99817,20.99958 250.99507,-15.99969 327.99356,1.99996" opacity="0.5" stroke-opacity="null" stroke-width="1" stroke=“#000" fill="none"/>
  <text fill="#fff" font-size="28" x=“50%" y="0">
    <textPath xlink:href="#textPath">
      利益点利益点利益点
    </textPath>
  </text>
</svg>

查阅了一下资料,在这篇文章 http://blog.csdn.net/salmonellavaccine/article/details/43041981 ,看到可以使用 <textPath> 的 text-anchor 和 startOffset 来实现居中的效果。

text-anchor: 文本相对于起始点的对齐方式。使用 middle 是居中。 startOffset: 离起始点的相对位置。

<svg viewBox="0,0,332,48">
  <path id="textPath" d="m0.749997,39.860256c92.99817,20.99958 250.99507,-15.99969 327.99356,1.99996" opacity="0.5" stroke-opacity="null" stroke-width="1" stroke=“#000" fill="none"/>
  <text fill="#fff" font-size="28">
    <textPath xlink:href=“#textPath"  text-anchor="middle" startOffset="50%">
      利益点利益点利益点
    </textPath>
  </text>
</svg>

一个有意思的地方:text-anchor 也是 的属性。也就是说, 使用 text-anchor="middle” 和 dx/x = “50%” 也可以实现居中。

leeenx avatar Jul 11 '17 11:07 leeenx