在 JavaScript 和 HTML 中下载 SVG 的按钮?
Button for downloading SVG in JavaScript & HTML?
浏览器中呈现了一张 SVG 图像。我想要下面的按钮来下载 SVG。看起来 download
使用正确的 mimetype 是正确的选择。
尝试:
<div id="container"></div>
<button id="download">Download SVG</button>
function downloadSVG() {
const svg = document.getElementById('container').innerHTML;
/*console.info(btoa(svg));
document.getElementById('svg').src = `data:image/svg+xml;utf8,${document.createTextNode(svg).textContent}`;
console.info('src:', document.getElementById('svg').src, ';');*/
const element = document.createElement('a');
const mimeType = 'image/svg+xml'; // 'image/svg+xml;utf8';
element.href = `${mimeType},${document.createTextNode(svg).textContent}`;
element.target = '_blank';
element.mimeType = mimeType;
element.download = 'w3c.svg';
element.id = 'downloader';
document.body.appendChild(element);
element.click();
document.getElementById('downloader').remove();
}
可运行示例:https://stackblitz.com/edit/typescript-mpk8ui
但是我得到了一个损坏的 SVG 文件。我的真实代码存在类似问题(我得到一个空的 SVG)。
下载数据必须是blob原始数据。
function downloadSVG() {
const svg = document.getElementById('container').innerHTML;
const blob = new Blob([svg.toString()]);
const element = document.createElement("a");
element.download = "w3c.svg";
element.href = window.URL.createObjectURL(blob);
element.click();
element.remove();
}
这应该可以解决问题。
浏览器中呈现了一张 SVG 图像。我想要下面的按钮来下载 SVG。看起来 download
使用正确的 mimetype 是正确的选择。
尝试:
<div id="container"></div>
<button id="download">Download SVG</button>
function downloadSVG() {
const svg = document.getElementById('container').innerHTML;
/*console.info(btoa(svg));
document.getElementById('svg').src = `data:image/svg+xml;utf8,${document.createTextNode(svg).textContent}`;
console.info('src:', document.getElementById('svg').src, ';');*/
const element = document.createElement('a');
const mimeType = 'image/svg+xml'; // 'image/svg+xml;utf8';
element.href = `${mimeType},${document.createTextNode(svg).textContent}`;
element.target = '_blank';
element.mimeType = mimeType;
element.download = 'w3c.svg';
element.id = 'downloader';
document.body.appendChild(element);
element.click();
document.getElementById('downloader').remove();
}
可运行示例:https://stackblitz.com/edit/typescript-mpk8ui
但是我得到了一个损坏的 SVG 文件。我的真实代码存在类似问题(我得到一个空的 SVG)。
下载数据必须是blob原始数据。
function downloadSVG() {
const svg = document.getElementById('container').innerHTML;
const blob = new Blob([svg.toString()]);
const element = document.createElement("a");
element.download = "w3c.svg";
element.href = window.URL.createObjectURL(blob);
element.click();
element.remove();
}
这应该可以解决问题。