渐变用jquery填充SVG

时间:2018-01-06 09:22:11

标签: jquery css svg jquery-svg radial-gradients

有没有办法用两种或三种渐变颜色填充SVG。使用以下方法,我可以用一种颜色填充特定的SVG路径。并且可以使用径向渐变但它无法处理动态方式。颜色需要在SVG代码中定义。因此,我希望使用两种或三种颜色作为渐变来填充SVG路径,如下所示使用jquery。是否有可能使用keith-svg插件执行此操作?

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

1 个答案:

答案 0 :(得分:3)

如@Robert_Longson所述,您可以动态创建RadialGradient元素,然后将其应用于fill属性:

这是一种非常基本的方式,需要改进才能将颜色和不同属性视为变量

$("#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,只需更改颜色和/或其他属性:

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>

相关问题