【问题标题】:How to fill a shape with the inverse of its background in SVG?如何在 SVG 中填充与背景相反的形状?
【发布时间】:2017-04-14 12:42:25
【问题描述】:

如何创建形状,例如一个矩形,它反转(异或?)它后面的所有颜色?

我尝试了失败:

<filter
id="invert">
<feColorMatrix
in="BackgroundImage"
values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0 "/>
<feComposite
operator="in"
in2="SourceGraphic"/>
</filter>
<svg>
  <rect x="10" y="10" width="50" height="50" fill="blue"></rect>
  <rect x="20" y="20" width="50" height="50" fill="blue" style="filter: url(#invert);"></rect>
</svg>

http://codepen.io/anon/pen/bqXPPZ

【问题讨论】:

    标签: svg svg-filters


    【解决方案1】:

    BackgroundImage 是几乎所有浏览器都不支持的输入,并且在下一个过滤器规范中正式弃用。

    你的选择是:

    • 复制背景图像中的任何内容,然后使用 feImage 将其导入过滤器,以便您可以使用它
    • 使用非标准 CSS 背景过滤器:invert(100%) - 仅在最近的 webkit 中支持(也不是 Chrome)
    • 使用 CSS background-blend 和 mix-blend(仅限最近的浏览器)示例:

    .content {
      background-image: url("http://stylecampaign.com/blog/blogimages/SVG/fox-1.svg");
      background-size: 600px; 
      position: absolute;
      top: 40px;
      left: 30px;
      width: 700px;
      height: 800px;
    }
    
    .inverter {
      background: white;
      position: absolute;
      top: 200px;
      left: 300px;
      width: 300px;
      height: 100px;
      mix-blend-mode: exclusion;
    }
    <div class="content">
      <div class="inverter"/>
    </div>
    • 您的最后一个选择是使用反转 SVG 过滤器将原始内容分层到内容的反转版本下方,然后在反转版本上使用蒙版以裁剪为所需的形状。

    <svg width="800px" height="600px">
      <defs>
        <filter id="invert">
          <feComponentTransfer>
            <feFuncR type="table" tableValues="1 0"/>
            <feFuncG type="table" tableValues="1 0"/>
            <feFuncB type="table" tableValues="1 0"/>
            </feComponentTransfer>
        </filter>
        
         <mask id="mask-me">
          <circle cx="215" cy="180" r="100" fill="white" />
        </mask>
      </defs>
      
        <image width="400" height="400" x="20" y="20" xlink:href="http://stylecampaign.com/blog/blogimages/SVG/fox-1.svg" />
      <image width="400" height="400" x="20" y="20" filter="url(#invert)" xlink:href="http://stylecampaign.com/blog/blogimages/SVG/fox-1.svg" mask="url(#mask-me)"/>
    
    </svg>

    【讨论】:

    • 谢谢。不幸的是,我无法让其中任何一个工作,但我也不确定我是否完全理解它们。看来,选项 1 已退出,因为我正在使用用户创建的 svg。我需要它至少在 Firefox 中也能工作,所以选项 2 似乎不适用。对于选项 3,我不知道这应该如何工作。您可以发布一个工作示例吗?选项 4 也是如此。
    • 发布的例子
    • 谢谢!我还不确定如何以这种方式获得反转颜色。您发布的示例取决于某些前景色。但是,反转与它无关。也许我使用了错误的术语?我的意思是我希望背景颜色通过它的反转来交换,白色黑色,红色青色,绿色洋红色,蓝色黄色等。也许我只需要选择某个前景在您的示例中使用颜色以获得结果?如果您有 GIMP,您可以尝试颜色 > 反转。这就是我的意思。
    • 这些做你想做的——记住这些图纸有透明的黑色,而不是白色的背景。如果你在白色背景上作画,你应该得到你想要的。
    • 如果您愿意完全迁移到 SVG,那么上面的最后一个选项将适用于 IE 10+
    猜你喜欢
    • 1970-01-01
    • 2011-09-10
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 2019-01-28
    • 2016-08-02
    • 2022-01-25
    相关资源
    最近更新 更多