I want to use drop-shadow to implement a shadow effect for a Polygon. However, I noticed that when the polygon has a semi-transparent color, the shadow area becomes visible through the polygon. I would like the shadow to only appear near the border of the polygon, similar to the visual effect achieved using box-shadow. Thanks for any help!

Here is my codepen: https://codepen.io/cactusxx/pen/qBgygqE

.rect1 {
  width: 150px;
  height: 150px;
  background-color: rgb(122, 122, 0, 0.5);
  margin: 50px;
  box-shadow: 10px 10px 10px purple;
}

polygon {
  fill: rgb(122, 122, 0, 0.5);
  filter: drop-shadow(10px 10px 5px purple);
}

<div class="rect1">
</div>

<svg width=200px height=200px>
  <polygon points="50,50 60,180 180,160"> </polygon>
</svg>
2

There are 2 best solutions below

1
SyndRain On BEST ANSWER

A simple workaround is to apply the opacity on the container instead. However, this will cause the shadow to look lighter than those that are not semi-transparent, which could be acceptable depending on your need.

.original-example {
  fill: rgb(122, 122, 0, 0.5);
  filter: drop-shadow(10px 10px 5px purple);
}

.semi-transparent-container {
  opacity: 0.5;
}

polygon {
  fill: rgb(122, 122, 0);
  filter: drop-shadow(10px 10px 5px purple);
}
<svg width=200px height=200px>
  <polygon class="original-example" points="50,50 60,180 180,160"> </polygon>
</svg>

<svg class="semi-transparent-container" width=200px height=200px>
  <polygon points="50,50 60,180 180,160"> </polygon>
</svg>

<hr class="solid">

<svg width=200px height=200px>
  <polygon points="50,50 60,180 180,160"> </polygon>
</svg>

<svg class="semi-transparent-container" width=200px height=200px>
  <polygon points="50,50 60,180 180,160"> </polygon>
</svg>

1
Jacob On

Instead of applying a shadow to the triangle directly, I created a line around the edge of the triangle and applied the shadow to the line.

<div class="rect1">
</div>

<svg width="200px" height="200px">
  <defs>
    <!-- Gaussian Blur for Lines -->
    <filter id="lineBlur" x="-50%" y="-50%" width="200%" height="200%">
      <feGaussianBlur in="SourceGraphic" stdDeviation="5"/>
    </filter>
  </defs>
  <!-- Semi-Transparent Polygon -->
  <polygon points="50,50 60,180 180,160" fill="rgba(122, 122, 0, 0.5)">
  </polygon>
  <!-- Separate Lines for Each Edge with Shadow Effect -->
  <g filter="url(#lineBlur)">
    <!-- Top Edge -->
    <line x1="50" y1="50" x2="60" y2="180" stroke="purple" stroke-width="1" transform="translate(0, 5)"/>
    <!-- Left Edge -->
    <line x1="60" y1="180" x2="180" y2="160" stroke="purple" stroke-width="1" transform="translate(5, 5)"/>
    <!-- Right Edge -->
    <line x1="180" y1="160" x2="50" y2="50" stroke="purple" stroke-width="1" transform="translate(5, 0)"/>
  </g>
</svg>