2

I'm trying to save the elements i'm creating with svg.js as a .svg file automatically after they are created. The library has the svg() method to export SVG but I haven't found examples to learn how to use it. For example, if I want to save the rect I create in the code below, how could I do it?

html:

<!DOCTYPE html>
<html>
<head>
  <title>SVG.js</title>
  <script src="https://cdn.jsdelivr.net/npm/@svgdotjs/[email protected]/dist/svg.min.js"></script>
</head>
<body>

</body>
</html>

js:

var draw = SVG().addTo('body').size(300, 300);
var rect = draw.rect(100, 100).attr({ fill: '#f06' });
8
  • What do you mean with "saving shapes as SVG files"? Because that's not a thing. You can save SVG documents as SVG file, but individual shapes are not a thing, you could save their outerHTML code as snippet, but then it's not an SVG file: it would most certainly fail SVG validation because it's missing the parts that need to go around it. Commented Mar 29, 2020 at 22:50
  • My bad. I meant SVG elements inside the SVG document. For example the rect element or the whole document as well.
    – Bejuco
    Commented Mar 29, 2020 at 23:01
  • Then it sounds like you're asking github.com/svgdotjs/svg.js/issues/131, and I can strongly recommend searching the issue trackers of open source you use, because that's generally the first place to ask (SO is your last resort). Commented Mar 29, 2020 at 23:04
  • I took a look on that but the svg.export.js description says: As of version 2 of SVG.js, this functionality is included in the main library. Therefore this plugin is obsolete if you are using version 2 and up. I'm gonna try and use it anyway.
    – Bejuco
    Commented Mar 29, 2020 at 23:08
  • This is why I'm asking, because I didn't find information in the svg.js repo/docs nor the issue trackers.
    – Bejuco
    Commented Mar 29, 2020 at 23:14

1 Answer 1

2

On http://svgjs.dev there is a searchbar where you can just search for export and you will find what you are looking for:

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()

Now you have generated a string containing your svg. To download this string as a file (creating a file), a quick google search gives you a nice solution:

function downloadString(text, fileType, fileName) {
  var blob = new Blob([text], { type: fileType });

  var a = document.createElement('a');
  a.download = fileName;
  a.href = URL.createObjectURL(blob);
  a.dataset.downloadurl = [fileType, a.download, a.href].join(':');
  a.style.display = "none";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(function() { URL.revokeObjectURL(a.href); }, 1500);
}

// downloadString("a,b,c\n1,2,3", "text/csv", "myCSV.csv")
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.