是否可以将SVG的<text>/<tspan>设置为固定宽度?

7
我想将文本向右对齐,此时我需要将文本固定宽度。因为文本内容是动态添加的。
<text>
  <tspan x="421" y="15" text-anchor="right"
     baseline-shift="0%" kerning="0" 
     font-family="Arial" font-weight="bold"
     font-size="12" fill="#490275" xml:space="preserve">
       This is entered by user.
</tspan>
</text>

1
你试过了吗? - Brett DeWoody
你是在谈论文本换行吗?如果是的话,请查看以下链接:https://dev59.com/MG445IYBdhLWcg3wM3bx、https://dev59.com/eXRB5IYBdhLWcg3w4bOv以及https://www.w3.org/Graphics/SVG/WG/wiki/Proposals/Wrapping_Text。 - Ruskin
只需在 SVG 的 CSS 中设置字体为“等宽字体”,就完成了。 - vsync
1个回答

5
我认为你的尝试已经接近成功了,你只是使用了错误的text-anchor值。如果你使用text-anchor="end",它将使文本对齐到元素的右侧。
因此,我们可以将tspanx位置设置为100%,再加上text-anchor="end",无论长度如何,文本都会被定位到右侧。

<svg width="100%" height="110">
  <text>
  <tspan x="100%" y="15" text-anchor="end"
     baseline-shift="0%" kerning="0" 
     font-family="Arial" font-weight="bold"
     font-size="12" fill="#490275" xml:space="preserve">
       This is entered by user.
</tspan>
</text>
  Sorry, your browser does not support inline SVG.  
</svg>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接