How to create a transparency gradient mask using an SVG filter

drarmstr picture drarmstr · Feb 6, 2014 · Viewed 14.4k times · Source

I am currently using an SVG gradient to apply a fade-out effect for paths. This allows the path to start at 100% opacity at x0 and fade out to 0% at x1, wherever those may be for the particular path it is applied to:

This works great when applying to the stroke style of the above path.

However, the problem is that by using the stroke style I cannot apply other stroke styles and it defaults to black. What I would like is to style the stroke using whatever color I want and then apply a gradient to the stroke-opacity or apply an SVG filter to create the fade-out effect. I tried messing with SVG filters and using feComponentTransfer with feFuncA, but wasn't able to get something that worked right.

The stroke color needs to be individually calculated for each path. So, the solution of setting the color in the gradient wouldn't scale very well.

Answer

Erik Dahlström picture Erik Dahlström · Feb 21, 2014

Does it need to be a gradient or a filter? I would suggest using a <mask> that contains a rect with a gradient applied, but I'm not sure about the requirements you have.

<svg>	
  <defs>
    <linearGradient id="fadeGrad" y2="1" x2="0">
      <stop offset="0.5" stop-color="white" stop-opacity="0"/>
      <stop offset="1" stop-color="white" stop-opacity=".5"/>
    </linearGradient>

    <mask id="fade" maskContentUnits="objectBoundingBox">
      <rect width="1" height="1" fill="url(#fadeGrad)"/>
    </mask>
  </defs>

  <path
    d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z"
    fill="green"
    stroke="red"
    mask="url(#fade)"
  />
</svg>

See a similar example here.