首页 > 解决方案 > 使用 SVG 过滤器为文本添加边框

问题描述

我从这里学到了使用过滤器为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>
  </defs>
<text filter="url(#solid)" x="20" y="50" font-size="50">solid background</text>
</svg>

标签: htmlsvgsvg-filters

解决方案


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

<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>


推荐阅读