我正在使用 Javascript 计算 svg
元素中的 path
和 circle
的值。我可以将正确的 HTML 代码注入(inject)到 HTML 页面中,但是没有绘制圆圈/svg。
这是通过 Javascript 注入(inject)到我的 HTML 中的内容
<svg>
<circle cx="115" cy="110" r="50"></circle>
<path d="M115,110 L115,0 A50,50 1 0,1 190,35 z"></path>
</svg>
如果我将此代码复制并粘贴到不同的 .html
文件中并运行它,我会得到一个形状(不完全是圆形)。这不会发生在我的实际网页中。
如果我将上面的代码直接放在html文件中(即不使用Javascript函数动态计算和注入(inject)它),我可以让形状出现。
我正在使用 Angular.js,如果这有影响的话。
我认为我的 Javascript 中没有错误,因为注入(inject)到 html 页面中的代码在其他地方也能正常工作,但如果有帮助,我可以发布我的 Javascript 代码。没有任何样式会阻止 SVG 的出现。这几乎就像我需要告诉浏览器重新加载/重新绘制/重新解析 HTML,但我不确定。
感谢您的帮助。
编辑:
这是我的 javascript 代码。
/*
<svg>
<circle cx="115" cy="115" r="110"></circle>
<path d="M115,115 L115,5 A110,110 1 0,1 190,35 z"></path>
</svg>
*/
Sector.prototype.draw = function() {
// Create our svg element
var svg = document.createElement('svg');
// Create and set up our circle element
var circ = document.createElement('circle');
circ.setAttribute('cx', this.startX);
circ.setAttribute('cy', this.startY);
circ.setAttribute('r', this.radius);
//Create and set up our path element
var p = document.createElement('path');
var dForPath = this.dString(this.startX, this.startY, this.radius, this.angle);
p.setAttribute('d', dForPath);
// Add our circle and path to the svg
svg.appendChild(circ);
svg.appendChild(p);
return svg;
};
和我的用法
var sec = new Sector(115, 115, 110, 7);
var c = sec.draw();
document.getElementById('circleTest').appendChild(c);
// Weird issue. The following line makes the svg appear;
// without it, the shape isn't drawn at all.
// http://stackoverflow.com/questions/21347833/html-svg-not-drawing-works-in-other-pages
document.getElementById('circleTest').innerHTML += '';
最佳答案
您不能将 createElement 与 SVG 一起使用,您必须改用 createElementNS 即
var svg = document.createElement('svg');
应该是
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
并且您需要对正在创建的所有其他 SVG 元素执行相同的操作。
您发现的 innerHTML 变通方法将修复 namespace ,但最好首先正确创建元素。
关于javascript - HTML SVG 未绘制(在其他页面中有效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21347833/