Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

opacity

svg

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?

like image 222
ChrisD Avatar asked Jan 17 '13 19:01

ChrisD


2 Answers

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.

like image 147
Thomas W Avatar answered Oct 21 '22 10:10

Thomas W


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>
like image 29
TuukkaH Avatar answered Oct 21 '22 09:10

TuukkaH