I have an SVG file created in Inkscape. I want to use xmlHttpRequest to import the svg file and then inject the data from the <g>
element into the HTML.
我在Inkscape中创建了一个SVG文件。我想使用xmlHttpRequest导入svg文件,然后将
HOWEVER. The xml response for some reason omits the g element. I can see this when I evaluate the XMLResponse in the browser's debug console. Why is this happening, and how can I fix it?
然而。由于某种原因,xml响应省略了g元素。当我在浏览器的调试控制台中评估XMLResponse时,我可以看到这一点。为什么会发生这种情况,我该如何解决?
Here's what the XMLResponse puts out
这是XMLResponse推出的内容
SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="7e3" width="7e3" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" viewBox="0 0 7000 7000">
<metadata>
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
<dc:title/>
</cc:Work>
</rdf:RDF>
</metadata>
<g>
<path d="m2757.3 5004.4-680.5-398.2-481.1 1037.3 168.3-770.3-1135.1-137 784.6-77.9-220.5-1122l316.57 722.13 998.9-556.4-588.96 524.23z" fill="#b80000"/>
<path d="m3412.4 2163.2-160.35-542.71-560.16-80.386 466.6-320.21-96.649-557.59 448.72 344.81 500.43-264.22-189.27 533.31 405.93 394.29-565.7-15.206z" fill="#c5e100"/>
<path d="m5368.2 4458.8-2316.6-2010.7 2271.3 3360.5-934.5-1243.8-1614.2 420 2282.8-768.5-2327 530.8 2258.9 1074.5-149.6-2017.6 490.3-524.8-2267.1 1484.9 2756.7-1066.1-2366.8 1127 1764.8 768.5 723-848.5-721.5-2303.9z" transform="matrix(.81493 0 0 .84227 1190.8 811.58)" fill="#1643bf"/>
</g>
</svg>
Javascript
var svg = document.getElementsByTagName("svg")[0];
var g = svg.getElementsByTagName("g")[0];
xmlHTTP = new XMLHttpRequest();
xmlHTTP.onload = function() {
if (this.readyState == 4 && this.status == 200) {
draw();
};
xmlHTTP.open("GET", "drawing.svg", true);
xmlHTTP.send();
function draw(){
var svgFile, extG;
svgFile = xmlHTTP.responseXML;// <---evaluates without the g element from the svg file
extG = svgFile.getElementsByTagName("g");
svg.replaceChild(extG[0],g);
};
1 个解决方案
#1
0
As I pointed out in the comments, you cannot use regular Dom methods on SVG before getting the SVG as a DOM object.
正如我在评论中指出的那样,在将SVG作为DOM对象之前,不能在SVG上使用常规Dom方法。
The best way to do this is something like:
最好的方法是这样的:
var svg=httpresponse.getDocumentElement();
var g=svg.getElementsByTagName('g');
Variable g
then will contain a live collection of g
elements.
变量g然后将包含g元素的实时集合。
#1
0
As I pointed out in the comments, you cannot use regular Dom methods on SVG before getting the SVG as a DOM object.
正如我在评论中指出的那样,在将SVG作为DOM对象之前,不能在SVG上使用常规Dom方法。
The best way to do this is something like:
最好的方法是这样的:
var svg=httpresponse.getDocumentElement();
var g=svg.getElementsByTagName('g');
Variable g
then will contain a live collection of g
elements.
变量g然后将包含g元素的实时集合。