2017-02-28 4 views
-2

私はd3.jsを使用し、本質的にインタラクティブな動的グラフをプロットしています。すべてがsvgコンテナに保存されているので、そのコンテナをcorelDrawなどのソフトウェアで編集できる.svgまたは.pngファイルとして保存します。私はもちろん、これをグーグルでオンラインで多くのものを見てみましたが、何も理解できませんでした。ある方向のどんな助けも評価されます。 ありがとうございます 更新 - @Jaco、私はここにサンプルコードを入れました。svgコンテナを.svgファイルとして保存するためのツールキットが一切ない方法ですか?

<!DOCTYPE html> 
<meta charset="utf-8"> 
<style> 
</style> 
<body> 
<script src="d3.js"></script>//I'm using the d3 library source code locally 
<script>//code here which reads a json file (local) and shows a graph when opened in browser, part of it is here where I declare svg and keep appending the stuff to it for drawing. 
var svg = d3.select("body").append("svg") 
.attr("width", width) 
.attr("height", height); 
//here I append circles to the svg and texts (labels) and links 
//some functions are declare to control the behaviour 
//nodes are appended as circles (one class) 
</script> //I use the id as svg 

答えて

1

下記のSVGを保存するための基本的な例を参照してください。また、スタイルを追加した場合は、スタイルを処理する必要があります。

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="svg-container"></div> 
 
<button id="svg-save" type="button">Save</button> 
 
<script> 
 
    $(document).ready(function() { 
 
    var width = 100; 
 
    var height = 100; 
 
    var svg = d3.select("#svg-container").append("svg") 
 
     .attr("width", width) 
 
     .attr("height", height); 
 

 
    var circle = svg.append("circle") 
 
     .attr("cx", 30) 
 
     .attr("cy", 30) 
 
     .attr("r", 20) 
 
     .attr("fill","red") 
 
    }); 
 
    
 
    $('#svg-save').click(function() { 
 
    var svg = document.getElementById('svg-container'); 
 
    //you need to clone your SVG otherwise it will disappear after saving 
 
    var clone = svg.cloneNode(true); 
 
    var svgDocType = document.implementation.createDocumentType('svg', "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"); 
 
    var svgDoc = document.implementation.createDocument('http://www.w3.org/2000/svg', 'svg', svgDocType); 
 

 
    svgDoc.replaceChild(clone, svgDoc.documentElement); 
 
    var svgData = (new XMLSerializer()).serializeToString(svgDoc); 
 
    var a = document.createElement('a'); 
 
    a.href = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgData.replace(/></g, '>\n\r<')); 
 
    a.download = 'downloaded.svg'; 
 
    a.innerHTML = 'download the svg file'; 
 

 
    //Hack alert: create a temporary link to download the svg 
 
    document.body.appendChild(a); 
 
    a.click(); 
 
    document.body.removeChild(a); 
 

 
}); 
 
</script>

+0

答えてくれてありがとう、私はそれの少しを得るが、どのように私はこれが正確に動作するのですか。では、ここでjavascriptを使用してコード化したHTMLファイルをどこで指定するのですか、このコードスニペットは私のコードに入りますか? –

+1

この例では、 'svg-container'と同じ' id'を持つsvgコンテナの内容を取得し、スタンドアロンのSVGファイルとして再フォーマットします。コードの簡略化されたバージョンを投稿したのであれば、おそらくダウンハンドを減らした方がいいでしょう。 – Jaco

+0

こんにちは@Jaco、私は謝罪し、ここでサンプルコードを編集して貼り付けました。 –

関連する問題