Pregunta

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.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top