在Javascript中生成SVG

在Javascript中生成SVG,javascript,svg,Javascript,Svg,我正在尝试用Javascript加载SVG。我经常这样做并取得成功,但这次它有一个奇怪的回报 这是我的JS var xmlns = 'http://www.w3.org/2000/svg'; var container = document.getElementById('svgContainer'); var svg = document.createElementNS(xmlns, 'svg'); svg.setAttribute('xmlns', xmlns); svg.setAttrib

我正在尝试用Javascript加载SVG。我经常这样做并取得成功,但这次它有一个奇怪的回报

这是我的JS

var xmlns = 'http://www.w3.org/2000/svg';
var container = document.getElementById('svgContainer');
var svg = document.createElementNS(xmlns, 'svg');
svg.setAttribute('xmlns', xmlns);
svg.setAttribute('version', '1.2');
var defs = document.createElementNS(xmlns, 'defs');
var lg = document.createElementNS(xmlns, 'linearGradient');
lg.setAttribute('id', 'lg');
defs.appendChild(lg);
var stop1 = document.createElementNS(xmlns, 'stop');
stop1.setAttribute('offset', '0');
stop1.setAttribute('style', 'stop-color:#ffffff;stop-opacity:1');
lg.appendChild(stop1);
var stop2 = document.createElementNS(xmlns, 'stop');
stop2.setAttribute('offset', '1');
stop2.setAttribute('style', 'stop-color:#000000;stop-opacity:1');
lg.appendChild(stop2);
var rg = document.createElementNS(xmlns, 'radialGradient');
rg.setAttribute('cx', '171.20810');
rg.setAttribute('cy', '196.85463');
rg.setAttribute('r', '200.00000');
rg.setAttribute('fx', '171.20810');
rg.setAttribute('fy', '196.85463');
rg.setAttribute('id', 'rg');
rg.setAttribute('xlink:href', '#lg');
rg.setAttribute('gradientUnits', 'userSpaceOnUse');
rg.setAttribute('gradientTransform', 'matrix(1.040418,0.796229,-0.814518,1.064316,153.4218,-150.4353)');
defs.appendChild(rg);
svg.appendChild(defs);
var g = document.createElementNS (xmlns, 'g');
g.setAttribute('transform', 'scale(0.2,0.2)');
svg.appendChild(g);
container.appendChild(svg);
var path = document.createElementNS (xmlns, 'path');
path.setAttribute('d', 'M 450.00000 255.00000 A 200.00000 205.00000 0 1 1  50.000000,255.00000 A 200.00000 205.00000 0 1 1  450.00000 255.00000 z');
path.setAttribute('style', 'opacity:1.0000000;fill:url(#rg);fill-opacity:1.0000000;fill-rule:evenodd;stroke:none;stroke-width:8.0000000;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1');
g.appendChild(path);
因此,它以适当的顺序生成完美的HTMLDOM元素,但它没有显示任何内容。当我从源代码复制HTML并粘贴它时,它呈现HTML而不是Javascript,但它是完全相同的代码

你可以看到来源

奇怪的是,当我把径向梯度放在DOM中时,它起作用了。你可以从中看到它

那我该怎么做呢?这个问题在所有浏览器上都存在

谢谢你的帮助

===编辑===

在Robert Longson的帮助下,我成功地解决了这个问题,请检查它

您不能使用setAttribute设置xlink:href,您必须使用setAttributeNS,例如

var xlinkns = 'http://www.w3.org/1999/xlink';
rg.setAttributeNS(xlinkns, 'xlink:href', '#lg');

以这种方式更改JSFIDLE可以使其在Firefox上工作。我没有测试过其他UAs,但它们也应该可以工作。

没有在Chrome上工作,但我改为:rg.setAttributeNS(“,'xlink:href','#lg');这是成功的!!非常感谢你!