看看这个演示:https://codepen.io/Alexander9111/pen/VwLaaPe?editors=1010 https://codepen.io/Alexander9111/pen/VwLaaPe?editors=1010
代码(修改自https://stackoverflow.com/a/19885344/9792594 https://stackoverflow.com/a/19885344/9792594):
function downloadSVGasTextFile() {
const base64doc = btoa(unescape(encodeURIComponent(document.querySelector('svg').outerHTML)));
const a = document.createElement('a');
const e = new MouseEvent('click');
a.download = 'download.svg';
a.href = 'data:text/html;base64,' + base64doc;
a.dispatchEvent(e);
}
downloadSVGasTextFile();
您将 svg 编码为 64 位字符串,然后将其用作锚标记的 href,然后分派单击事件以将 svg 文本文件下载为 download.svg
如果你想保存图像,例如.png,那么你可以先将svg图像绘制到cnavas中,然后将其下载为.png,
UPDATE
我修改了答案和演示,现在包括下载为文本文件 .svg 或下载为图像文件 .pnghttps://codepen.io/Alexander9111/pen/VwLaaPe https://codepen.io/Alexander9111/pen/VwLaaPe:
HTML:
<svg>
...
</svg>
<br/>
<button id="downloadPNG">Download .png</button>
<button id="downloadSVG">Download .svg</button>
JS:
function downloadSVGAsText() {
const svg = document.querySelector('svg');
const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));
const a = document.createElement('a');
const e = new MouseEvent('click');
a.download = 'download.svg';
a.href = 'data:image/svg+xml;base64,' + base64doc;
a.dispatchEvent(e);
}
function downloadSVGAsPNG(e){
const canvas = document.createElement("canvas");
const svg = document.querySelector('svg');
const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));
const w = parseInt(svg.getAttribute('width'));
const h = parseInt(svg.getAttribute('height'));
const img_to_download = document.createElement('img');
img_to_download.src = 'data:image/svg+xml;base64,' + base64doc;
console.log(w, h);
img_to_download.onload = function () {
canvas.setAttribute('width', w);
canvas.setAttribute('height', h);
const context = canvas.getContext("2d");
//context.clearRect(0, 0, w, h);
context.drawImage(img_to_download,0,0,w,h);
const dataURL = canvas.toDataURL('image/png');
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(canvas.msToBlob(), "download.png");
e.preventDefault();
} else {
const a = document.createElement('a');
const my_evt = new MouseEvent('click');
a.download = 'download.png';
a.href = dataURL;
a.dispatchEvent(my_evt);
}
//canvas.parentNode.removeChild(canvas);
}
}
const downloadSVG = document.querySelector('#downloadSVG');
downloadSVG.addEventListener('click', downloadSVGAsText);
const downloadPNG = document.querySelector('#downloadPNG');
downloadPNG.addEventListener('click', downloadSVGAsPNG);