Gradient fills SVG with jquery

Is there a way to fill the SVG with two or three gradient colors. Using the following path, I can fill a specific SVG path with one color. And the radial gradient can be used, but it cannot work dynamically. Colors must be defined in SVG code. So I want to fill the SVG path using two or three colors as a gradient as follows using jquery. And is there any way to do this using the keith-svg plugin?

$("#canvas-area").click(function (event) {
      $(event.target).css('fill', _'#000');
})
+4
source share
1 answer

As @Robert_Longson noted, you can dynamically create a RadialGradient element and then apply it to the fill property:

,

$("#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>
Hide result

RadialGradient / :

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>
Hide result
+4

Source: https://habr.com/ru/post/1691824/


All Articles