Home > Mobile >  How do I merge multiple radial gradients onto a single SVG alpha mask?
How do I merge multiple radial gradients onto a single SVG alpha mask?

Time:03-02

My application uses SVG to render a virtual tabletop scene. The user can place tokens on top of the scene and the background is revealed for a given radius around the token. Tokens can reveal different radii.

Initially I used clip paths to reveal circles around the tokens with hard edges. This works nicely with no issue.

Now, I wonder if I can create "smooth" transitions from revealed to unrevealed by using, for example, a circle with a radial gradient (from white in the center to black to the edges) and use the combined circles as a mask to apply to the scene.

My attempt uses a single radial gradient definition and multiple <circle fill="url(#gradient")> within a <mask> which is then applied to the underlying image. However as you can see in the image below, the gradients do not smoothly blend into each other.

These radial gradients do not merge nicely

I understand why this is happening but I'm looking for another way to achieve the effect with SVG.

CodePudding user response:

Specify your gradients with alpha rather than black/white and this works just fine. (Please post test code in future)

<svg width="800px" height="800px" viewBox="0 0 400 400">
  <defs>
  <radialGradient id="myGradient">
  <stop offset="0%" stop-color="white" stop-opacity="100%"/>
  <stop offset="40%" stop-color="white" stop-opacity="100%"/>
  <stop offset="60%" stop-color="white" stop-opacity="60%"/>
  <stop offset="95%" stop-color="white" stop-opacity="0%"/>
</radialGradient>

<mask id="myMask" maskContentUnits="objectBoundingBox">
  <circle cx=".25" cy=".25" r=".25" fill="url(#myGradient)"/>
  <circle cx=".25" cy=".55" r=".20" fill="url(#myGradient)"/>
        <circle cx=".65" cy=".35" r=".35" fill="url(#myGradient)"/>
</mask>
  </defs>
  
  <image href="https://nostalgiacentral.com/wp-content/uploads/2015/12/snakesladders5.jpg" x="10" y="10" height="200" width="200"  mask="url(#myMask)" preserveAspectRatio="xMinYMin slice"/>
  
</svg>

  •  Tags:  
  • svg
  • Related