How to keep the color of an SVG "filter: drop-shadow()" regardless of the background?

1.5k views Asked by At

I tried to add the red shadow around an SVG image based on the CodePen example at https://codepen.io/dudleystorey/pen/EaMQBj. However, the color turns into purple when the background color is blue. How to keep the color as red no matter what the background color or image is? Any help is appreciated.

#robbie {
background-color: blue;
  display: inline-block;
  background-repeat: no-repeat;
  background-size: cover;
}
#robbie img {
filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12,
Color='#444')";
  filter: url(#drop-shadow);
  -webkit-filter: drop-shadow(0 0 15px rgba(255,0,0,0.9));
  filter: drop-shadow(0 0 15px rgba(255,0,0,0.9));
}
<div id="robbie">
  <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/robby-the-robot.png" alt>
</div>

<svg height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="drop-shadow">
  <feGaussianBlur in="SourceAlpha" stdDeviation="2.2"/>
  <feOffset dx="12" dy="12" result="offsetblur"/>
  <feFlood flood-color="rgba(0,0,0,0.5)"/>
  <feComposite in2="offsetblur" operator="in"/>
  <feMerge>
  <feMergeNode/>
  <feMergeNode in="SourceGraphic"/>
  </feMerge>
</filter>
</svg>

1

There are 1 answers

0
Michael Mullany On

The purple is created by the browser when it takes the progressively more transparent red shadow and composites it on top of a solid blue. To fix this, you need to change the shadow to solid red. You can't use the CSS filter for this, you have to use the SVG version.

<svg height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="drop-shadow">
  <feGaussianBlur in="SourceAlpha" stdDeviation="2.2"/>
  <feOffset dx="12" dy="12" result="offsetblur"/>
  <feFlood flood-color="rgba(255,0,0,1)"/>
  <feComposite in2="offsetblur" operator="in"/>
  <feMerge>
  <feMergeNode/>
  <feMergeNode in="SourceGraphic"/>
  </feMerge>
</filter>
</svg>

Note that this only works when your source is fully opaque. If you want a solid shadow around a partially transparent image then there are additional manipulations you need.