Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save svg canvas to local filesystem

Is there a way to allow a user, after he has created a vector graph on a javascript svg canvas using a browser, to download this file to their local filesystem?

SVG is a total new field for me so please be patient if my wording is not accurate.

like image 222
dr jerry Avatar asked Mar 20 '10 17:03

dr jerry


People also ask

Can you save an SVG?

You can use the Save As feature to save to the SVG format directly. Choose File > Save As from the Menu Bar. You can create a file and then choose File > Save As to save the file. In the save window, change the Format to SVG (svg) and then click Save.

How do I download a SVG file?

Once you're on a web page, click the extension's icon next to the URL bar and a new tab will open showing you all the SVG files it found on the page. You can copy an SVG file to your clipboard, download only the few you need, or click the 'Download all SVGs' button to add them all to a zipped file and download them.

Can I use SVG in canvas?

To draw SVG onto canvas, you need to use SVG image. Firstly, use the <foreignObject> element which contains the HTML. After that, you need to draw the SVG image into the canvas.


2 Answers

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

like image 189
The Who Avatar answered Sep 18 '22 15:09

The Who


Using FileSaver.js

saveAs(new Blob([SVG_DATA_HERE], {type:"image/svg+xml"}), "name.svg") 
like image 42
Eli Grey Avatar answered Sep 20 '22 15:09

Eli Grey