Save SVG as an Image
Let’s start with a simple D3 example. I have slightly modified this example here by placing the SVG contents into a div instead of body and I added a “save as image” button and function. Here is a gist of the function:
So, we grab the D3.js generated SVG, convert it into a base64 dataurl, and stick it into an IMG tag. Since this is still SVG, lets load it into an an actual image and load that image into a CANVAS object. At this point we can grab the PNG dataurl from CANVAS and insert that into an IMG tag on the page. Now, we have an actual PNG image with base64 encoded image data in the source. Using the HTML5 link download attribute we can force the browser to download that image programatically. Here is the result and our new function looks like this:
Now, this is pretty cool, especially that you can programmatically download the image file but how about actually creating an image file on the client side? We can use a blob to store the image data and then drop it into a blob url. I have covered Blobs before in my Drag and Drop Image Upload to Imgur example and Making Video Screenshots with HTML5 demo but that code leveraged the HTML FileReader functionality while here we can just convert image data into a binary format with atob and DataView. Here is the final result and our canvas data to binary image function:
Finally, lets finish this of with a drag and drop SVG to PNG image converter. You can check out the source to see how that works.
SVG Crowbar – Chrome-specific bookmarklet that extracts SVG nodes and accompanying styles from an HTML document and downloads them as an SVG file