Creating an SVG in Javascript using FabricJS and downloading it locally

simplesvg

This following short example creates an canvas image using FabricJS. Pressing the draw, then save button creates an SVG representing this image, then creates a file based on this image using session local storage. Finally it adds a download link to this file to the html. The user can then download the SVG file to local storage. This has only been tested on Firefox.

UPDATE: FabricJS 1.4.0 appears to have issues where line coordinates get randomly offset. I’ve updated the example below to link to 1.4.13, however 1.4.0 is still linked as the latest CDN version on the FabricJS site. The example below will work with 1.4.0, but I don’t recommend using it.

<html>

<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.13/fabric.min.js"></script>
<script langauge="javascript">

  var m_canvas;

  function do_draw() {
    // create a wrapper around native canvas element (with id="c")
    m_canvas = new fabric.Canvas('c');

    // create a rectangle object
    var rect = new fabric.Rect({
      left: 100,
      top: 100,
      fill: 'red',
      width: 20,
      height: 20
    });

    // "add" rectangle onto canvas
    m_canvas.add(rect);
  }

  function do_save() {
    var filedata=m_canvas.toSVG(); // the SVG file is now in filedata

    var locfile = new Blob([filedata], {type: "image/svg+xml;charset=utf-8"});
    var locfilesrc = URL.createObjectURL(locfile);//mylocfile);

    var dwn = document.getElementById('dwn');
    dwn.innerHTML = "<a href=" + locfilesrc + " download='mysvg.svg'>Download</a>";
  }
</script>

<body>

<canvas id='c'></canvas>
<input type="button" id="drawBtn" value="draw" onclick="do_draw()"></input>

<input type="button" id="saveBtn" value="save" onclick="do_save()"></input>
<div id='dwn'></div>

</body>
</html>