Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a transparency gradient mask using an SVG filter

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:

<svg>
    <linearGradient id="gradient_to_transparent" x1="0%" x2="100%">
        <stop offset="0" stop-opacity="1"></stop>
        <stop offset="1" stop-opacity="0"></stop>
    </linearGradient>

    <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"
        style="stroke:url(#gradient_to_transparent);"
    />
</svg>

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.

like image 732
drarmstr Avatar asked Feb 06 '14 19:02

drarmstr


People also ask

How do you create a gradient in SVG?

To use a gradient, we have to reference it from an object's fill or stroke attributes. This is done the same way you reference elements in CSS, using a url . In this case, the url is just a reference to our gradient, which I've given the creative ID, "Gradient". To attach it, set the fill to url(#Gradient) , and voila!

Can you have gradient in SVG?

SVG provides for two types of gradients: linear gradients and radial gradients. Once defined, gradients are then referenced using 'fill' or 'stroke' properties on a given graphics element to indicate that the given element shall be filled or stroked with the referenced gradient.


1 Answers

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.

like image 74
Erik Dahlström Avatar answered Oct 15 '22 02:10

Erik Dahlström