Save generated SVG with svg.js as .svg file

Viewed 1148

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/svg.js@3.0/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' });
1 Answers

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")
Related