SVG with drop-shadow blurry on mobile browser

2020-06-23 09:17发布

问题:

i am struggling to make work SVG icons with drop-shadow on as much as possible platforms.

I am using following simple CSS for that:

.test{
  width: 14px;
  height: 14px;
  background-image: url("../images/test.svg");
  background-repeat: no-repeat;
  opacity: 0.8;
  -webkit-filter: drop-shadow(1px 1px 0px #E0E0E0);
}

On Desktop browsers like Chrome, Firefox & IE its working good. But on mobile Browser the problems begin: In Chrome the icon gets blurry & in Firefox the drop-shadow is just ignored. When removing the drop-shadow, the icon will be clear again in Chrome, so i think it has something in common with the drop-shadow.

Anyone had the same problem and found maybe a solution for this?

回答1:

Just found the answer for it.
This problem occurs due to the way SVG filters are generated: Before a filter is applied, a bitmap image of the respective element is created which is then manipulated and layered on top. You can find a great explanation here.

To show svg images sharp on HDPI screens, you can try using the filterRes-property on the effect, which provides a pixel resolution for calculated svg effects, more on that here.
Use it like so:

<filter id="dropshadow" height="170%" filterRes="200">
  <feGaussianBlur in="SourceAlpha" stdDeviation="20"/>
  <feOffset dx="0" dy="2" result="offsetblur"/>
  <feMerge> 
    <feMergeNode/>
    <feMergeNode in="SourceGraphic"/>
  </feMerge>
</filter>
<path id="icon" fill="#fff" style="filter:url(#dropshadow)" d="..."></path>
</svg>

Say you add background-size: contain to your css - the drawn container will presumably be 14px x 14px. To render the shadow with sufficient resolution for retina displays (eg. factor 2), you should take a healthy value of 30 for filterRes. This is not ideal, but it seems like it is the only working alternative at the moment. Kind of defeats the reason for using svg at all.