jquery - 使用 jquery 渐变填充 SVG

标签 jquery css svg jquery-svg radial-gradients

有没有办法用两种或三种渐变颜色填充 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,您只需更改颜色和/或其他属性:

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>

关于jquery - 使用 jquery 渐变填充 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125941/

相关文章:

java - GEF 中的 SVG 图像

javascript - jQuery 和 Chrome - 查找按钮 Hook

javascript - 如何在整个网站上保留切换状态?

jquery - 单击时如何将div下拉值放入文本框

javascript - SVG 和 RevealJS 中的鼠标位置

angular - 属性 'contentDocument' 在类型 'HTMLElement' 上不存在

javascript - jquery 移动弹出对话框 : Cannot read property 'is' of undefined

javascript - 位置 : fixed; element doesn't work correctly on iOS 上的触摸事件

javascript - 如果页面上不存在特定类,则添加类

html - 表格单元格宽度问题