【问题标题】:Javascript edit SVGJavascript 编辑 SVG
【发布时间】:2014-02-21 11:23:58
【问题描述】:

我想直接在JS中编辑一个SVG文件,不用任何框架。

基本上我有一个 SVG 主文件,其中应该包含一些子 SVG。

我已经在 Ajax 中检索了这些孩子的内容,但我想将它们插入到 SVG 标记中。

例如,我创建了一个新标签

var svgInclude= document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgInclude.setAttribute('id', 'include_1');
svgInclude.setAttribute('height', widthVis);
svgInclude.setAttribute('width', widthVis);
svg.appendChild(svgInclude);

当我想插入从这个函数中检索到的 XML 数据时:

function loadXMLDoc(url, cb) {
  var xmlhttp;
  if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
  else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) cb(xmlhttp.responseText);
  };
  xmlhttp.open('GET', url, true);
  xmlhttp.send();
}

使用:

loadXMLDoc(host + '/svg/frame_panto_v2.svg', function(xml) {
  svgInclude.innerSVG(xml);
});

它不起作用,说Uncaught TypeError: Object #<SVGSVGElement> has no method 'innerSVG'。我也尝试过使用innerHTML,但我得到了同样的错误。

如何将下载的 SVG 文件“粘贴”到 SVG 标签中?

感谢您的帮助。

【问题讨论】:

标签: javascript svg


【解决方案1】:

使用DOMParser 执行此操作。

var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");

这将为您获取一个 SVG 文档,您可以使用 doc.documentElement 获取内容并使用 importNodeappendChild 添加它。

【讨论】:

  • 谢谢,但我现在收到以下错误:Uncaught HierarchyRequestError: A Node was inserted somewhere it doesn't belong.。我认为这是因为 SVG 标头。我该如何解决?
  • 用这个代码解决了:someElement.appendChild(someElement.ownerDocument.importNode(doc.documentElement, true));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2016-05-06
  • 2011-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多