D3 chart to canvas/PNG with download link

by jdcast

HTML

<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script> 
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script> 
<section>
    <header><h1>SVG:</h1></header>
    <div id='svg-container'>
        <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
          <rect x="50" y="20" width="150" height="100" style="fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9" />
        </svg>
    </div>
</section>
<section>
    <header><h1>Canvas:</h1></header>
<canvas id="svg-canvas"></canvas>
</section>
<section>
    <header><h1>PNG:</h1></header>
<img id="svg-img" />
</section>
<section>
    <a id="basic">download</a>
</section>

CSS

section {
    height: 175px;
}

JavaScript

var $container = $('#svg-container'),
    // Canvg requires trimmed content
    content = $container.html().trim(),
    canvas = document.getElementById('svg-canvas');

    // Draw svg on canvas
    canvg(canvas, content);

    // Change img be SVG representation
    var theImage = canvas.toDataURL('image/png');
    $( "#basic" ).click(function() {
        window.open(theImage);
    });
    $('#svg-img').attr('src', theImage);

// the canvg call that takes the svg xml and converts it to a canvas
canvg(canvas, $("svg").html());

// the canvas calls to output a png
var canvas = document.getElementById("svg-canvas");
var img = canvas.toDataURL("image/png");
alert(img);