svg - svg 中的多行文本

标签 svg

我知道如何在矩形中绘制文本线:

<svg width="200" height="100">
  <rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="white"/>
  <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">TEXT</text>    
</svg>

现在我想要中断文本。它应该大致如下所示:

line.....
   TEXT
line.....

我尝试使用<br>在文本中,但这不起作用。

这应该在现代浏览器(Chrome、Edge、Firefox...)中呈现

结果应如下所示:

line1-text-line2-in-box

最佳答案

多行录音,使用tspan很方便

在 svg 中只有绝对定位。 xy坐标确定文本第一个字符的位置`

<tspan>标签有助于缩短标签输入 <text>

否则,我必须为每一行文本编写标记 <text> 的完整形式。

<svg width="40%" height="40%" viewBox="0 0 200 100">
  <rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="white"/>
  <text  fonnt-size="48"   > 
     <tspan x="4em" y="1.5em">line1 ...</tspan>
    <tspan x="50%" y="50%" text-anchor="middle" >TEXT</tspan>
    <tspan x="4em" y="4.5em">line2 ...</tspan>
   </text>    
</svg>

更新

如果您需要在 SVG 中使用 CSS 规则定位多文本,请使用 foreignObject

<svg width='200' height='100' style="border:1divx solid gray; ">
     
     <rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="none"/>
  <foreignObject x="0" y="0" width="200" height="100">
       <style>
          .container 
		  {
    	     width: 200px;
			 font-size:20px;
		  }
         .line
		 {
		     padding:0.3em 0.3em 0.3em 3em;
         }
          .text
		  {
		  text-align: center;
		  vertical-align: middle;
		  }
		  
       </style>
       <body xmlns="httdiv://www.w3.org/1999/xhtml">
           <div class="container">
              <div class="line">line1 .....</div>
              <div class="text"> TEXT</div> 
              <div class="line">line2 .....</div>
           </div>
        </body>   
  </foreignObject>
</svg>    

关于svg - svg 中的多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58750651/

相关文章:

javascript - Angular2渲染器: Svg rect is rendered but not showing in page

javascript - 如何在分配功能后删除 onmouseout 事件?

html - 如何修复 SVG 顶部和左侧笔划截断?

具有 0px 间隙的 CSS 网格中的 SVG 显示背景颜色

javascript - 如何在 SVG 中包含 jQuery SVG 源?

html - SVG 不显示在 Safari 的 img 标签中

css - 某些 SVG 文件不适用于 Safari

SVG 文本路径重复文本

javascript - 无法在 d3.js 中的同一页面上生成两个饼图

macos - Chrome 中的 SVG strip