HTML SVG 不绘图(适用于其他页面)

mat*_*mer 2 html javascript svg angularjs

我正在使用 Javascript计算 apath和元素circle内的值svg。我可以将正确的 HTML 代码注入到 HTML 页面中,但没有绘制圆/svg。

这是 Javascript 注入到我的 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>
Run Code Online (Sandbox Code Playgroud)

如果我将此代码复制并粘贴到另一个.html文件中并运行它,则会出现一个形状(不完全是圆形)。这不会发生在我的实际网页中。

如果我将上面的代码直接放在 html 文件中(即不使用 Javascript 函数动态计算和注入它),我可以让形状出现。

我正在使用 Angular.js,如果这有区别的话。

我不认为我的 Javascript 中存在错误,因为注入 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;
};
Run Code Online (Sandbox Code Playgroud)

和我的用法

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 += '';
Run Code Online (Sandbox Code Playgroud)

Rob*_*son 5

您不能将 createElement 与 SVG 一起使用,您必须使用 createElementNS 代替,即

var svg = document.createElement('svg');
Run Code Online (Sandbox Code Playgroud)

应该

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
Run Code Online (Sandbox Code Playgroud)

并且您需要对您正在创建的所有其他 SVG 元素执行相同的操作。

您找到的innerHTML 解决方法将修复名称空间,但最好首先正确创建元素。