SVG.js - Export nested SVG with Clip intact?

41 Views Asked by At

I have an SVG.js canvas that has a nested artwork and a nested UI on top that controls it. I want to export the artwork which is clipped. The issue is the Defs and SVG headers are at the root so they’re not part of the nested SVG’s getter response (svgString below).

canvas = SVG()
artwork = canvas.nested()
artworkLimit = canvas.rect(100,100)
clip = canvas.clip().add(artworkLimit)
artwork.clipWith(clip)
/* Add Artwork Here */
svgString = artwork.svg()

I was hoping that there was a built-in way to export a nested SVG as you see it on the screen but I can't find it in the docs. I've also tried putting the clip within the nested SVGs and making containers but the Defs is always on the root SVG object.

Is the intended solution?

  • A. Export the whole SVG.js object but using the SVG(function(node){...}) modifier to exclude the the UI and retain the Defs and headers and also undo the rotation, scaling and panning that is done to the artwork. Downside is the user will see it flicker as it has to reposition.
  • B. Just use the nested artboard SVG getter and do some find and replace on the string to insert the headers and defs. Fiddly but helps the user experience
  • C. Rebuild the artwork layer in a second SVG canvas/object and export that instead. Canvas can be off screen and no change in what the user sees. (Also better for bitmaps exports)
  • D. Something better?
1

There are 1 best solutions below

2
On BEST ANSWER

If the original svg can be destroyed after the export you can use the following. Otherwise you might need to clone first:

const nestedNode = reference to your nested nestedNode.addTo(someDiv)
rootSvg.defs().addTo(nestedNode)
nestedSvg.svg() // svg string

So you are basically moving the nested svg into its own div (which makes it a root svg) and then transplant the defs.

If your root svg has a viewbox you might need to copy that as well.