SVG - 具有背景颜色和圆形边框的文本

hol*_*321 3 svg

是否可以用纯 SVG 制作这样的东西?

在此输入图像描述

没有 Javascript、固定大小或 html。

我尝试使用 rect 元素,但这不是一个灵活的解决方案。

我尝试使用过滤器,但这是一个没有圆角的解决方案。

Mic*_*any 12

您可以通过两种替代方式使用过滤器来执行此操作:

  1. 进行泛光,模糊,然后剪掉低不透明度,然后将剩余的不透明度调至最大
  2. 通过 feImage 走私圆角矩形并使用相对大小调整来拉伸它

在这两种情况下,填充都是相对的,因此如果文本太长,圆角将溢出过滤区域。与 CSS 不同,您无法在 SVG 中组合相对和绝对大小(至少 SVG 1.1 如此)。所以这已经是你能得到的最好的了。

由于您确实正在寻找 HTML 文本行为,但您希望它在 SVG 中,因此您可能需要考虑使用foreignObject 并以这种方式嵌入 HTML 文本。

<svg width="800px" height="600px">
<defs>
  <filter id="rounded-corners" x="-5%" width="110%" y="0%" height="100%">
<feFlood flood-color="#FFAA55"/>
<feGaussianBlur stdDeviation="2"/>
<feComponentTransfer>
  <feFuncA type="table"tableValues="0 0 0 1"/>
</feComponentTransfer>

<feComponentTransfer>
  <feFuncA type="table"tableValues="0 1 1 1 1 1 1 1"/>
</feComponentTransfer>
   <feComposite operator="over" in="SourceGraphic"/>
  </filter>
  
   <filter id="rounded-corners-2" primitiveUnits="objectBoundingBox">
<feImage preserveAspectRatio="none" width="110%" height="110%" x="-5%" y="0%"  xlink:href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' x='0px' y='0px' viewBox='0 0 400 40' height='40' width='400'%3E%3Crect fill='red' x='0' y='0' rx='10' ry='10' width='400' height='40'/%3E%3C/svg%3E"/>
   <feComposite operator="over" in="SourceGraphic"/>
  </filter> 
  
  
  </defs>

  
  <text filter="url(#rounded-corners)" x="20" y="40" style="font-size:30">Blur & opacity filter</text>
  
  <text filter="url(#rounded-corners)" x="20" y="80" style="font-size:30"> But the x padding is relative and overflows with long text</text>
  
<text filter="url(#rounded-corners-2)" x="20" y="140" style="font-size:30">feImage and a rect filter</text>
  
<text filter="url(#rounded-corners-2)" x="20" y="180" style="font-size:30">But you still can't get away from relative padding</text>

</svg>
Run Code Online (Sandbox Code Playgroud)