svgfade

SVG fade color of object


I want to fade the fill color of a SVG circle from one color to another color, like from red to black.

<svg height="100" width="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" fade-to="black"/>
</svg>

What would I do in place of the fade-to="black"?


Solution

  • You will want to use the radial gradient to have this work. You can play around with the offset numbers for the desired effect.

    <svg height="100" width="100">
      <defs>
        <radialGradient id="myGradient">
          <stop offset="10%" stop-color="red" />
          <stop offset="95%" stop-color="black" />
        </radialGradient>
      </defs>
    
      <!-- using my radial gradient -->
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="url('#myGradient')"/>
    </svg>

    Edit:
    After doing some more research and figuring out how to do what you were suggesting, this is what I came up with:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
        .redBall{
            fill: red;
            z-index: 1;
            -webkit-animation: pulsateMore 3s ease-out;
            -webkit-animation-iteration-count: infinite; 
        }
    
        @-webkit-keyframes pulsateMore {
            0% { 
            fill: red;
            }
            50% { 
            fill: black;
            }
            00% { 
            fill: red;
            }
        }
        </style>
        <!-- <link rel="stylesheet" href="style.css" /> -->
    </head>
    <body>
        <svg height="100" width="100">
            <circle class="redBall" cx="50" cy="50" r="40"/>
        </svg>
    </body>
    </html>

    You can manipulate this code from here to have a JavaScript function that will have an onClick event that will trigger the circle to go from red to black, instead of pulsating.