svg - 如果两个部分不透明的形状重叠,我可以在它们重叠的地方只显示一个形状吗?

标签 svg opacity

例如,如果您有一个由圆形和矩形组成的简单“ spy 玻璃”形状,并且两者的轮廓都是部分透明的,您能否阻止在两个形状重叠的地方有效降低不透明度?

最佳答案

您可以使用过滤器来调整不透明度值。假设两个形状的不透明度值为 0.5,那么您希望使两者重叠的区域的不透明度值也为 0.5。

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="300px">
  <filter id="constantOpacity">
    <feComponentTransfer>
      <!-- This transfer function leaves all alpha values of the unfiltered
           graphics that are lower than .5 at their original values.
           All higher alpha above will be changed to .5.
           These calculations are derived from the values in
           the tableValues attribute using linear interpolation. -->
      <feFuncA type="table" tableValues="0 .5 .5" />
    </feComponentTransfer>
  </filter>
  
  <line x2="300" y2="300" stroke="black" stroke-width="10"/>
  <path d="M0 150h300" stroke="blue" stroke-width="10"/>
  <g filter="url(#constantOpacity)">
    <rect x="50" y="50" width="150" height="150" opacity=".5" fill="green" id="rect1"/>
    <rect width="150" height="150" opacity=".5" fill="red" id="rect2"
          x="100" y="100"/>
  </g>
</svg>

您可以看到添加过滤器可以让背景以恒定的强度透过。但是,形状的颜色会变得更苍白、更灰暗(除非两种颜色相同)。也许你可以妥协,用 tableValues 稍微减少 alpha 值。属性如 0 .5 .75而不是 0 .5 .5 .

关于svg - 如果两个部分不透明的形状重叠,我可以在它们重叠的地方只显示一个形状吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14386642/

相关文章:

javascript - 基于滚动条位置的 Div 不透明度

javascript - svg 元素在 Chrome 中隐藏/显示时重置

html - 加载时出现不需要的 SVG 动画延迟

javascript - 链接 SVG 路径

javascript - 如何在两点之间创建弯曲的 SVG 路径?

html - 关于我的不透明度 slider 的建议(纯 CSS,无 JS)

html - 如何使用 CSS 降低元素背景的不透明度?

jquery - 检测不透明度何时发生变化

CSS3 变换不透明度脉动

svg - 如何围绕椭圆制作 SVG 圆动画