2017-06-02 102 views
0

在我的應用程序中,用戶可以在SVG中使用React渲染小圖。我想將SVG上傳到我的服務器。上傳一個反應渲染的SVG

如何將SVG渲染爲Javascript圖像,以便我可以將其上傳到我的服務器? Google搜索不會返回有意義的結果。

回答

1

這不是具體的反應,而是一個在文檔<svg>轉換爲SVG文件,你只需要它的標記序列化到字符串(CF XMLSerializer),將所得字符串附加在一個Blob和上傳的Blob您服務器。

但是,如果你想有一個完整的獨立的SVG文件,與文檔類型和命名空間,這裏是如何做到這一點的例子:

function svgNodeToBlob(node) { 
 
    // first an doctype 
 
    var svgDocType = document.implementation.createDocumentType('svg', "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"); 
 
    // then a new SVG Document 
 
    var svgDoc = document.implementation.createDocument('http://www.w3.org/2000/svg', 'svg', svgDocType); 
 
    // set its documentElement to our root svg node (well a clone of it) 
 
    svgDoc.replaceChild(node.cloneNode(true), svgDoc.documentElement); 
 
    // serialize the document 
 
    var svgData = (new XMLSerializer()).serializeToString(svgDoc); 
 
    // convert to a blob 
 
    var blob = new Blob([svgData], { 
 
    type: 'image/svg+xml; charset=utf8' 
 
    }); 
 
    return blob; 
 
} 
 

 
var blob = svgNodeToBlob(document.querySelector('svg')); 
 
// from here you can send the blob to your server 
 

 
// for the demo, we'll just make an downloadable link from it 
 
var a = document.querySelector('a'); 
 
a.href = URL.createObjectURL(blob); 
 
a.download = 'mycoolsvgfile.svg';
<svg> 
 
    <rect width="50" height="50" x="20" y="10"/> 
 
</svg> 
 
<a>download as file</a>

但是請注意,所有外部資源那對你的節點有影響的東西不會在文件上(也就是說,如果你使用外部樣式表做CSS的樣式)。在這種情況下,您必須在克隆節點內追加克隆這些外部元素,然後將其附加到SVG文檔中。