If two partially opaque shapes overlap, can I show only one shape where they overlap?

丶灬走出姿态 提交于 2019-12-01 07:14:28

You can use a filter to tweak the opacity value. Say, both shapes have an opacity value of .5, then you want to make the area where both overlap to have an opacity value of .5 as well.

<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

You can see that adding the filter lets the background shine through so to say with constant intensity. However, the color of the shapes gets a paler, more grayish appearance (unless both colors are identical). Maybe you can go with a compromise, reducing the alpha value slightly less with a tableValues attribute like 0 .5 .75 instead of 0 .5 .5.

If the shape is constructed as a single SVG path element, the overlaps don't sum up into a darker result.

If the shape is constructed of multiple SVG elements, the overlaps do sum up into a darker result.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="300px">
<!-- No summing here -->
<g>
    <path d="M10,10 L100,100 M10,100 L100,10" style="stroke: #000000; stroke-width: 10px; opacity: 0.5" />
</g>
<!-- Summing here -->
<g>
    <path d="M200,200 L290,290" style="stroke: #000000; stroke-width: 10px; opacity: 0.5" />
    <path d="M200,290 L290,200" style="stroke: #000000; stroke-width: 10px; opacity: 0.5" />
</g>
</svg>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!