CSS中形状的混合模式

7

假设我有一些圆:

<circle class="first">&nbsp;</circle>
<circle class="second">&nbsp;</circle>

以下是相关的CSS代码:
circle {
  border-radius: 50%;
  width: 100px;
  height: 100px;
  background: #000;
}

我该如何在重叠时获得以下效果?
最好使用CSS或canvas元素实现。 css circles overlap

如果您愿意使用SVG,您可以使用SVG滤镜来实现此目的。 - Michael Mullany
2个回答

9

一种可能的方法是使用mix-blend-mode属性,目前大部分浏览器似乎不支持此属性

以下是一个在Chrome和Firefox中可行的示例(感谢@vals)

body
{
  background-color: white;
}

.circle
{
  border-radius: 100px;
  background-color: white;
  width: 100px;
  height: 100px;
  float: left;
  mix-blend-mode: exclusion;
}

.circle:not(:first-child)
{
  margin-left: -20px;
}
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>

正如@vals所指出的,您需要为body(或父元素)设置background-color才能在Firefox中正常工作。

这里有两个关于此主题的好参考资料:

  1. https://css-tricks.com/basics-css-blend-modes/

选自此来源:http://codepen.io/chriscoyier/pen/tCykv

  1. https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode

2
Firefox的问题并不是由于白色背景覆盖在白色背景上引起的;body没有定义的背景。设置body {background-color:white;},它将在Chrome和FF中正常工作。顺便说一句+1。 - vals
@vals 非常感谢您的评论。这真的很有趣。我更新了答案并尝试更深入地调查 :) - Nico O

4

SVG

使用单个路径在<svg>中可以轻松实现该效果。

如果形状重叠,则fill-rule将是您要查找的内容,那么您获得的效果就是每个形状颜色相互重叠。

<svg width="500px" height="200px" viewBox="0 0 100 500">
  <path fill-rule="evenodd" d="
        M 50, 100
        m -75, 0
        a 75,75 0 1,0 150,0
        a 75,75 0 1,0 -150,0
        Z
        M 150, 100
        m -75, 0
        a 75,75 0 1,0 150,0
        a 75,75 0 1,0 -150,0
        Z
        M 250, 100
        m -75, 0
        a 75,75 0 1,0 150,0
        a 75,75 0 1,0 -150,0
        Z
        M 350, 100
        m -75, 0
        a 75,75 0 1,0 150,0
        a 75,75 0 1,0 -150,0
        Z
        M 450, 100
        m -75, 0
        a 75,75 0 1,0 150,0
        a 75,75 0 1,0 -150,0
        Z" />
</svg>


这绝对是一个好方法,如果你需要跨浏览器支持。不错。 - Nico O
@NicoO,我喜欢你的解决方案,但它的支持不足。 - Persijn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接