在新窗口中打开内联 SVG - Javascript

Bel*_*ian 10 javascript svg

我有一个<div>包含内联svg. 我想要一个svg在新选项卡/窗口中打开它的功能。我只想使用前端js,而不必保存svg任何地方。

如果我使用window.open(),它会将 svg 放在<html>我试图避免的标签中。

我基本上是想改变这个答案,但只剩下 svg 代码:https : //stackoverflow.com/a/21667339/1083923

//---print button---
    var printSVG = function()
    {
        var popUpAndPrint = function()
        {
            var container = $('#svgDiv');
            var width = parseFloat(container.getAttribute("width"))
            var height = parseFloat(container.getAttribute("height"))
            var printWindow = window.open('', 'PrintMap',
            'width=' + width + ',height=' + height);
            printWindow.document.writeln($(container).html());
            printWindow.document.close();
            printWindow.print();
            printWindow.close();
        };
        setTimeout(popUpAndPrint, 500);
    };
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 12

您可以将元素字符串化为有效的 SVG 文档并将其存储为 Blob,然后使用 blob:// URI 将您的新窗口指向该 Blob:

// we need to handle a user gesture to use 'open'
document.getElementById("btn").onclick = (evt) => {
  // grab your svg element
  const svg = document.querySelector("svg");
  // convert to a valid XML source
  const as_text = new XMLSerializer().serializeToString(svg);
  // store in a Blob
  const blob = new Blob([as_text], { type: "image/svg+xml" });
  // create an URI pointing to that blob
  const url = URL.createObjectURL(blob);
  const win = open(url);
  // so the Garbage Collector can collect the blob
  win.onload = (evt) => URL.revokeObjectURL(url);
};
Run Code Online (Sandbox Code Playgroud)

JS-fiddle 演示,因为 StackSnippet 的沙盒 iframe 不允许打开新窗口。