How to save svg canvas to local filesystem How to save svg canvas to local filesystem javascript javascript

How to save svg canvas to local filesystem


You can avoid a round trip to the server.

Base64 encode your SVG xml.

Then generate a link to that data. The user can right click on to save it locally.

// This example was created using Protovis & jQuery// Base64 provided by http://www.webtoolkit.info/javascript-base64.html// Modern web browsers have a builtin function to this as well 'btoa'function encode_as_img_and_link(){ // Add some critical information $("svg").attr({ version: '1.1' , xmlns:"http://www.w3.org/2000/svg"}); var svg = $("#chart-canvas").html(); var b64 = Base64.encode(svg); // or use btoa if supported // Works in recent Webkit(Chrome) $("body").append($("<img src='data:image/svg+xml;base64,\n"+b64+"' alt='file.svg'/>")); // Works in Firefox 3.6 and Webit and possibly any browser which supports the data-uri $("body").append($("<a href-lang='image/svg+xml' href='data:image/svg+xml;base64,\n"+b64+"' title='file.svg'>Download</a>"));}

The img tag works in Webkit, the link works in Webkit & Firefox, and may work in any browser which supports data-uri


Using FileSaver.js

saveAs(new Blob([SVG_DATA_HERE], {type:"image/svg+xml"}), "name.svg")


There is no need to do base64 encoding - you can create a link with raw SVG code in it. Here is a modified function encode_as_img_and_link() from The_Who's answer:

function img_and_link() {  $('body').append(    $('<a>')      .attr('href-lang', 'image/svg+xml')      .attr('href', 'data:image/svg+xml;utf8,' +  unescape($('svg')[0].outerHTML))      .text('Download')  );}