使用 SVG 过滤器为文本添加边框

Using SVG filter to add border to the text

我从 here 那里学会了使用 filter 为 SVG 中的 text 添加背景。 但是如何给文本添加边框呢?

<svg width="100%" height="100%">
  <defs>
    <filter x="0" y="0" width="1" height="1" id="solid">
      <feFlood flood-color="yellow"/>
      <feComposite in="SourceGraphic"/>
    </filter>
  </defs>
<text filter="url(#solid)" x="20" y="50" font-size="50">solid background</text>
</svg>

使用另一个稍微大一点的过滤器来创建边框。

<svg width="100%" height="100%">
  <defs>
    <filter x="0" y="0" width="1" height="1" id="solid">
      <feFlood flood-color="yellow"/>
      <feComposite in="SourceGraphic"/>
    </filter>
    <filter x="-0.005" y="-0.01" width="1.01" height="1.02" id="border">
      <feFlood flood-color="black"/>
      <feComposite in="SourceGraphic"/>
    </filter>
  </defs>
<g filter="url(#border)">
  <text filter="url(#solid)" x="20" y="50" font-size="50">solid background</text>
<g>
</svg>

看起来 Chrome 不支持对同一元素使用多个过滤器,但如果您的浏览器支持,例如Firefox 你可以避免额外的 <g> 元素...

<svg width="100%" height="100%">
  <defs>
    <filter x="0" y="0" width="1" height="1" id="solid">
      <feFlood flood-color="yellow"/>
      <feComposite in="SourceGraphic"/>
    </filter>
    <filter x="-0.005" y="-0.01" width="1.01" height="1.02" id="border">
      <feFlood flood-color="black"/>
      <feComposite in="SourceGraphic"/>
    </filter>
  </defs>
  <text filter="url(#solid) url(#border)" x="20" y="50" font-size="50">solid background</text>
</svg>