title: Get SVG from canvas element and save it
body: <p>Currently I'm creating a small application for a friend, who´s starting his PhD and needs to build some network graphs. So far everything works fine using the a Force Directed graph. The graphs nodes can be moved to style the layout.</p>
  
  <p><img src="https://i.imgur.com/SsGFz.png" /></p>
  
  <p>The thing I can't get my head around is:</p>
  
  <blockquote>
    <p><strong>»how to extract the data from the canvas and save it to a SVG file«</strong>.</p>
  </blockquote>
  
  <h3>What I tried:</h3>
  
  <p>I already tried accessing the image Data from the console with </p>
  
  <pre><code>var app.canvas = document.getElementById( 'graph-canvas' )
      .getContext( '2d' )
          .getImageData( 0, 0, 200, 200 );
  </code></pre>
  
  <p>and got an <code>(object) ImageData</code> in return. Now I can access the ↑ shown canvas data with <code>app.canvas.data</code>. (When I try too look up the values, the browser starts hanging and asks if the script should be stopped - Chrome &amp; FF latest).</p>
  
  <p>How would I go from here to get the SVG drawn and then saved by the click of a button?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>So far I found out how to draw the SVG and add an <code>image/png</code> element to it. How ever, it´s not displaying.</p>
  
  <pre><code>// Add the test SVG el:
  var svg = document.createElementNS( "http://www.w3.org/2000/svg", "svg" );
  svg.setAttribute( 'style', 'border: 1px solid black;' )
          .setAttribute( 'width', '600' )
          .setAttribute( 'height', '400' )
          .setAttributeNS(
              'http://www.w3.org/2000/xmlns/',
              'xmlns:xlink',
              'http://www.w3.org/1999/xlink'
          );
  
  // Call
  importCanvas( document.getElementById( 'infovis-canvas' ), svg ); 
  
  // Function: Add data to SVG
  function importCanvas( sourceCanvas, targetSVG ) 
  {
      // get base64 encoded png data url from Canvas
      var img_dataurl = sourceCanvas.toDataURL( "image/png" );
  
      var svg_img = document.createElementNS(
          "http://www.w3.org/2000/svg",
          "image"
      );
  
      svg_img.setAttributeNS(
          'http://www.w3.org/1999/xlink',
          'xlink:href',
          img_dataurl
      );
      jQuery( targetSVG.appendChild( svg_img ) )
          .appendTo( '#graph-container' );
  
      console.log( 'done' ); // Log &amp; confirm
  }
  </code></pre>
  
  <p>And finally the...</p>
  
  <pre><code>// ...resulting SVG element containing the image element
  &lt;svg style="border: 1px solid black;" width="600" height="400" xlink="http://www.w3.org/1999/xlink"&gt;&lt;image href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAA(...)
  </code></pre>
  
  <hr>
  
  <p><em>The UI works with jQuery UI, jQuery and the <a href="http://thejit.org/static/v20/Docs/files/Core/Core-js.html" rel="noreferrer">The Jit/InfoVIZ</a> library, so those are available.</em></p>