【问题标题】:How to append SVGs to a <div>?如何将 SVG 附加到 <div>?
【发布时间】:2017-05-10 22:46:24
【问题描述】:

虽然关于如何在 div 中附加 SVG 有很多答案,但我无法让它们中的任何一个为我工作。可能是因为我以前从未使用过 SVG。

所以,我在我的节点服务器上创建一个 SVG,然后创建一个 JSON 对象,其中包含一些其他数据以及 SVG

svgFiles.push({
   'file': svgDump, //This holds well created SVG
   'vp': JSON.stringify(viewport),
   'page': pageNum
});

然后将其作为对我的 angularjs 代码的响应发回。

$http({ ... }).then(function callback(resp) { // request to node server
  var svg = resp.data.file;
  var container = document.createElement('div');
  var oldContent = container.innerHTML; // There is going to be an array of objects with SVG data hence i need the 'APPEND' functionality
  // But currently assuming there is only 1 object for demo purpose
  container.innerHTML = oldContent + svg;
})

现在我已经将我的 SVG 保存在一个变量中,我希望将它附加到任何 DIV 中应该可以工作。

虽然它确实有效,但它都是纯文本,包括@font-face、src 等内容。

我确定我缺少某些东西或没有以正确的方式进行操作。我怎样才能做到这一点?

【问题讨论】:

    标签: javascript angularjs json svg


    【解决方案1】:

    在朋友的帮助下终于找到了解决方案。

    我需要做的就是:

    $http({ ... }).then(function callback(resp) { // request to node server
      var svg = resp.data.file;
      var container = document.createElement('div');
      var parser = new DOMParser();
      var doc = parser.parseFromString(svg, "image/svg+xml");
      container.appendChild(doc.documentElement);
    });
    

    【讨论】:

    • 使用 DOMParser 使 SVG 的渲染变得非常缓慢,但是当我直接在 DOM 中附加 SVG(不是像上面那样存储在字符串中)时,不会出现这样的延迟/性能问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2016-12-05
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 2021-04-18
    相关资源
    最近更新 更多