Search code examples
jquerycsssvgjquery-svgradial-gradients

Gradient fill SVG with jquery


Is there a way to fill SVG with two or three gradient colors. Using following way I can fill a particular SVG path by one color. And radial gradient can be used but it cannot handle dynamic way. Colors need to define within SVG code. So I want to fill SVG path using two or three colors as a gradient as following way using jquery. And is there any possibility to do this using keith-svg plugin?

$("#canvas-area").click(function (event) {
      $(event.target).css('fill', _'#000');
})

Solution

  • As @Robert_Longson commented you can create dynamically the RadialGradient element and then apply it to the fill property:

    This is a very basic way and need to be improved in order to consider colors and different properties as variable

    $("#canvas-area").click(function(event) {
      $('body').append('<svg id="grade-def"><defs><radialGradient id="grad" cx="50%" cy="50%" r="50%" fx="50%" fy="50%"><stop offset="0%" style="stop-color:red;stop-opacity:1" /><stop offset="100%" style="stop-color:blue;stop-opacity:1" /></radialGradient></defs></svg>');
      $(event.target).attr('fill', 'url(#grad)');
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <svg height="150" width="400" id="canvas-area">
      <ellipse cx="200" cy="70" rx="85" ry="55" fill="#000" />
      <text fill="#ffffff" font-size="45" font-family="Verdana" x="150" y="86">
      SVG</text>
    </svg>

    You can also have your RadialGradient already defined and you simply change the colors and/or other properties:

    let colors = ["green", "orange", "yellow", "brown", "blue", "red", "pink"]
    
    $("#canvas-area").click(function(event) {
      $(this).find('#grad stop').eq(0).css('stop-color', colors[Math.floor(Math.random() * 7)]);
      $(this).find('#grad stop').eq(1).css('stop-color', colors[Math.floor(Math.random() * 7)]);
      $(event.target).attr('fill', 'url(#grad)');
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <svg height="150" width="400" id="canvas-area">
    <defs>
    <radialGradient id="grad" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
          <stop offset="0%" style="stop-color:red;stop-opacity:1" />
          <stop offset="100%" style="stop-color:blue;stop-opacity:1" />
        </radialGradient>
    </defs>
      <ellipse cx="200" cy="70" rx="85" ry="55" fill="#000" />
      <text fill="#ffffff" font-size="45" font-family="Verdana" x="150" y="86">
      SVG</text>
    </svg>