在过去几个月里,我一直在处理椭球地球相关的代码,最近我已经完成了它。现在我的教授要求我把我做的图表发送给他,以SVG文件的形式。我知道在Python中,你可以将几行代码放入项目中来下载图像,但我不确定在JavaScript中该怎么做。我应该如何在JavaScript中实现呢?或者是否有更简单的方法?
请查看此演示:https://codepen.io/Alexander9111/pen/VwLaaPe?editors=1010
代码(修改自https://dev59.com/OGIj5IYBdhLWcg3wx38x#19885344):
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>
...
</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);
unescape
和 encodeURIComponent
的目的。 - artidataio