HTML SVG不绘图(在其他页面中工作)

时间:2014-01-25 07:16:45

标签: javascript html angularjs svg

我正在使用Javascript计算path元素中circlesvg的值。我可以将正确的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>

如果我将此代码复制并粘贴到另一个.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;
};

和我的用法

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 += '';

2 个答案:

答案 0 :(得分:3)

您不能将createElement与SVG一起使用,您必须使用createElementNS,即<。p>

var svg = document.createElement('svg');

应该是

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

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

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

答案 1 :(得分:1)

我可以通过添加行

来显示形状
document.getElementById('circleTest').innerHTML += '';

在我的svg注入circleTest的代码下面。我不确定为什么这解决了这个问题。