Search code examples
svgopacity

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


For example if you have a simple "spy glass" shape made of a circle and a rectangle and the outlines of both are partially transparent, can you stop the opacity effectively being decreased where the two shapes overlap?


Solution

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