用 jquery 渐变填充 SVG

Gradient fill SVG with jquery

有没有办法用两种或三种渐变颜色填充 SVG。使用以下方式,我可以用一种颜色填充特定的 SVG 路径。可以使用径向渐变,但不能处理动态方式。颜色需要在 SVG 代码中定义。所以我想使用两种或三种颜色作为渐变填充 SVG 路径,如下所示使用 jquery。有没有可能使用 keith-svg 插件来做到这一点?

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

正如@Robert_Longson 评论的那样,您可以动态创建 RadialGradient 元素,然后将其应用于填充 属性:

这是一个非常基本的方法,需要改进以便将颜色和不同的属性视为变量

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

您还可以定义 RadialGradient,然后只需更改颜色 and/or 其他属性:

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>