SVG.js

Import / export SVG

svg() as getter

returns string

Exporting the full generated SVG, or a part of it, can be done with the svg() method:

draw.svg()

Exporting works on individual elements as well:

var rect = draw.rect()
var svg  = rect.svg()

You can specify if you only want the content of the element to be exported instead of the element with its contents:

var children = draw.svg(false)

You can also specify an export modifier which is run on every node before exporting:

var roundedChildren = draw.svg(function(node) {
  node.round(4)
}, false)

Nodes can be even removed or replaced in this modifiers:

var tidied = draw.svg(function(node) {
  // remove all shapes with blue color
  if (node.fill() == 'blue') return false

  // replace with circles
  return new Circle().radius(5).fill(node.fill())
})

svg() as setter

returns itself

Importing is done with the same method by passing a string of svg as the first argument:

draw.svg('<g><rect width="100" height="50" fill="#f06"></rect></g>')

You can also import multiple children at once:

draw.svg('<rect><rect><rect>')

If you want to replace the current elemet with the imported, you can pass a flag:

group.svg('<rect><rect><rect>', true)

Note, that this call always returns the parent of the element svg() was called on. That is, because by replacing a node with multiple others nodes it is not clear which node to return. Thats why the parent is returned.

Import / export HTML or XML

Svg.js also supports handling html nodes and sometimes you are in need to import or export html.
For this case, you can use the html() method that will use the correct namespace on import.

draw.html('<div></div>) // import html
draw.html() // export

if you use svg.js to manipulate xml, you can use xml() together with a namespace

draw.xml('<my-element></my-element>, myNamespace) // import
draw.xml() // export
Fork me on GitHub