如何将SVG附加到< div> ;?
尽管有很多关于如何在div中添加SVG的答案,但是我无法为我工作.可能是因为我以前从未使用过SVG.
因此,我要在节点服务器上创建SVG,然后在其中添加其他一些数据以及SVG来创建JSON对象
Though there are many answers on SO on how to append an SVG in a div but i couldn't get any of them to work for me. May be because i've never worked with SVGs before.
So, i'm creating an SVG on my node server and then creating a JSON object with some other data along with SVG in it
svgFiles.push({
'file': svgDump, //This holds well created SVG
'vp': JSON.stringify(viewport),
'page': pageNum
});
,然后将其发送回我的angularjs代码.
and then sending it back as a response to my angularjs code.
$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中都可以正常工作.
Now that i've my SVGs saved in a variable, i expected that appending it in any DIV should work.
尽管它确实起作用,但它都是纯文本,包括诸如@ font-face,src等之类的东西.
我确定有些东西我遗漏了或者没有以正确的方式进行.我该如何实现?
Though it did work but it was all plain text including stuff like @font-face, src etc.
I'm sure there is something that i'm missing or not doing the right way. How can i achieve this?
最后在朋友的帮助下找到了解决方案.
我需要做的就是:
Finally found a solution for this with help of a friend.
All i needed to do was:
$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);
});