2017-06-02 2 views
0

私のアプリケーションでは、ユーザーはリアクションを使用してレンダリングしたSVGの小さな図を作成できます。私は私のサーバーにSVGをアップロードしたいと思います。リアクションレンダリングされたSVGをアップロードする

SVGをJavascript Imageにレンダリングするには、どうすればサーバーにアップロードできますか? Googleの検索結果は意味のある結果を返しません。

答えて

1

これは反応するものではなく、文書<svg>をsvgファイルに変換するには、そのマークアップを文字列(cf XMLSerializer)にシリアル化し、結果の文字列をBlobに追加してBlobをサーバ。

しかし、あなたは完全なスタンドアロンのSVG文書をしたい場合は、DOCTYPEと名前空間で、ここでそれを行う方法の例です:

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ドキュメントに追加する前に、クローンノード内にこれらの外部要素のクローンを追加する必要があります。

関連する問題