How to save an svg generated by raphael

房东的猫 提交于 2019-12-03 08:50:19

问题


Is there a way to save the SVG generated by raphael as an svg file. Note it only need to work in chrome.


回答1:


As stef commented, the BlobBuilder API is deprecated. Instead, use the Blob API.

Building on Andreas' answer, here is how I quickly got it to work:

svgString = r.toSVG();
a = document.createElement('a');
a.download = 'mySvg.svg';
a.type = 'image/svg+xml';
blob = new Blob([svgString], {"type": "image/svg+xml"});
a.href = (window.URL || webkitURL).createObjectURL(blob);
a.click();



回答2:


I came up with a solution using Raphael.Export, which gives me an valid svg/xml String (something that I couldn't get from the simply from the innerHTML of the DOM object that holds the svg) and Blobbuilder to create a url for a link which will I fire a click event at the end to save the file.

svgString = @paper.toSVG();
a = document.createElement('a');
a.download = 'mySvg.svg';
a.type = 'image/svg+xml';
bb = new(window.BlobBuilder || WebKitBlobBuilder);
bb.append(svgString);
blob = bb.getBlob('image/svg+xml');
a.href = (window.URL || webkitURL).createObjectURL(blob);
a.click();



回答3:


If you don't want to use the Rapahel.Export, you can directly get the svg from the dom, like that:

var svgString = document.getElementById('holder').innerHTML;
a = document.createElement('a');
a.download = 'mySvg.svg';
a.type = 'image/svg+xml';
blob = new Blob([svgString], {"type": "image/svg+xml"});
a.href = (window.URL || webkitURL).createObjectURL(blob);
a.click();

"holder" is the id of the div where is loaded Raphael : r = Raphael("holder"); Note that I think it won't work on old browser that doesn't handle svg




回答4:


For the part where you save the blob, I'd recommend https://github.com/eligrey/FileSaver.js/

or https://www.npmjs.com/package/angular-file-saver if you're using AngularJs



来源:https://stackoverflow.com/questions/10120975/how-to-save-an-svg-generated-by-raphael

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!