【问题标题】:HTML SVG Not Drawing (Works in Other Pages)HTML SVG 不绘图(在其他页面中工作)
【发布时间】:2014-02-16 08:12:36
【问题描述】:

我正在使用 Javascript 计算 svg 元素内的 path 和 circle 的值。我可以将正确的 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 += '';

【问题讨论】:

  • @RobertLongson 我已编辑问题以包含我的 Javascript。谢谢。

标签: javascript html angularjs svg


【解决方案1】:

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

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

应该是

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

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

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

【讨论】:

  • 谢谢!我是否还需要将createElementNS 用于我的path 和circle 元素?我需要为这些使用的namespaceURI 是什么?此外,是否有更好/更标准的方式将我的元素从 Javascript 插入 HTML?
  • 与我上面提供的相同的 namespaceURI。这是标准方式。
  • 太棒了!非常感谢您的帮助。
【解决方案2】:

我可以通过添加线条来显示形状

document.getElementById('circleTest').innerHTML += '';

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

【讨论】:

  • 4 年后,我遇到了同样的问题,而这种解决方法是使其工作的唯一方法。你找到原因了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
相关资源
最近更新 更多