Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

javascript - Importing external SVG (with WebKit)

The following works in Firefox 4, but not Chrome 10:

<svg:svg version="1.1">
    <svg:use xlink:href="some_file.svg#layer1"/>
</svg:svg>

This is a known bug in Chrome/WebKit, so there's nothing I can do about that except try to find a way to work around it. I thought about using an XMLHttpRequest to grab the external file and insert it into the svg element. Will that cause any problems? Are there better ways to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After you fetch the SVG document via XHR you will have a separate XML document in the xhr.responseXML property. Since you cannot legally move nodes from one document to another, you'll need to import the portion you want from one document into your target document before you can use it as part of that document.

The simplest way to do this is to use document.importNode():

var clone = document.importNode(nodeFromAnotherDoc,true);
// Now you can insert "clone" into your document

However, this does not work for IE9. To work around that bug, you can alternatively use this function to recursively recreate a node hierarchy in the document of choice:

function cloneToDoc(node,doc){
  if (!doc) doc=document;
  var clone = doc.createElementNS(node.namespaceURI,node.nodeName);
  for (var i=0,len=node.attributes.length;i<len;++i){
    var a = node.attributes[i];
    clone.setAttributeNS(a.namespaceURI,a.nodeName,a.nodeValue);
  }
  for (var i=0,len=node.childNodes.length;i<len;++i){
    var c = node.childNodes[i];
    clone.insertBefore(
      c.nodeType==1 ? cloneToDoc(c,doc) : doc.createTextNode(c.nodeValue),
      null
    );
  }
  return clone;
}

You can see an example of using XHR to fetch an SVG document and both techniques of importing the node on my website: http://phrogz.net/SVG/fetch_fragment.svg


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...