动态添加SVG渐变 [英] Dynamically adding a SVG gradient

查看:188
本文介绍了动态添加SVG渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个带路径的SVG容器。我想编辑它,所以路径的填充将是一个模式。这是我失败的尝试:

I have this SVG container with paths. I want to edit it, so the paths' fill will be a pattern. This is my failed attempt:

我添加了一个渐变:

$('svg defs').prepend('<linearGradient id="MyGradient"><stop offset="5%" stop-color="#F60" /><stop offset="95%" stop-color="#FF6" /></linearGradient>');

然后更改路径的填充:

$(base + ' svg path').each(function() {
    this.setAttribute('fill','url(#MyGradient)')
}

这不起作用。我错过了什么?

This doesn't work. What am I missing?

推荐答案

你的问题(你缺少)是jQuery在XHTML命名空间中创建新元素,而SVG元素必须在SVG命名空间中创建。不能在SVG元素的字符串中使用原始代码。

Your problem (what you are "missing") is that jQuery creates new elements in the XHTML namespace, while SVG elements must be created in the SVG namespace. You cannot use raw code in a string for SVG elements.

最简单的(无插件)方法是停止依赖jQuery这么多,只需使用简单的DOM方法来创建元素。是的,它比仅使用jQuery为你神奇地构造你的元素更加冗长......但jQuery在这种情况下不起作用。

The simplest (no-plugins) method is to stop leaning on jQuery so much and just use simple DOM methods to create the elements. Yes, it's more verbose than just using jQuery to magically construct your elements for you...but jQuery does not work in this case.

createGradient($('svg')[0],'MyGradient',[
  {offset:'5%', 'stop-color':'#f60'},
  {offset:'95%','stop-color':'#ff6'}
]);
$('svg path').attr('fill','url(#MyGradient)');

// svg:   the owning <svg> element
// id:    an id="..." attribute for the gradient
// stops: an array of objects with <stop> attributes
function createGradient(svg,id,stops){
  var svgNS = svg.namespaceURI;
  var grad  = document.createElementNS(svgNS,'linearGradient');
  grad.setAttribute('id',id);
  for (var i=0;i<stops.length;i++){
    var attrs = stops[i];
    var stop = document.createElementNS(svgNS,'stop');
    for (var attr in attrs){
      if (attrs.hasOwnProperty(attr)) stop.setAttribute(attr,attrs[attr]);
    }
    grad.appendChild(stop);
  }

  var defs = svg.querySelector('defs') ||
      svg.insertBefore( document.createElementNS(svgNS,'defs'), svg.firstChild);
  return defs.appendChild(grad);
}



使用图书馆



或者,您可以添加 Keith Woods的jQuery SVG插件,该插件具有许多常用SVG操作的便捷方法,包括创建线性渐变的能力。

Using a Library

Alternatively, you can include Keith Woods' "jQuery SVG" plugin that has a lot of convenience methods for common SVG operations, including the ability to create linear gradients.

这篇关于动态添加SVG渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆