用于在 JavaScript 和 HTML 中下载 SVG 的按钮?

A T*_*A T 4 html javascript anchor svg download

There's an SVG image that's rendered in the browser. I want a button below to download the SVG. Looks like download with proper mimetype is the way to go.

Attempt:

<div id="container"></div>
<button id="download">Download SVG</button>
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)

Runnable example: https://stackblitz.com/edit/typescript-mpk8ui

But I get a broken SVG file. Similar issue with my real code (I get an empty SVG).

sui*_*ish 6

下载数据必须是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();
}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题。

  • 您需要 OUTERHTML.. `const svg = document.getElementById('container').outerHTML;` 才能正常工作并摆脱 **此 XML 文件似乎没有与之关联的任何样式信息。文档树如下所示。** (2认同)