2017-02-28 38 views
-2

我使用d3.js並繪製了一個本質上是交互式的動態圖。一切都被保存在一個SVG容器中,現在我想將該容器保存爲.svg或.png文件,可以使用corelDraw之類的軟件進行編輯。我試着用谷歌搜索當然在網上搜索很多東西,但無法理解任何東西。任何方向的幫助將不勝感激。 謝謝 更新 - @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'標識svg容器的內容,並將其重新格式化爲獨立的SVG文件。如果您發佈了代碼的簡化版本,那麼這將會非常有用,否則您的代碼可能會減少。 – Jaco

+0

嘿@Jaco,我很抱歉,編輯並粘貼了一個示例代碼。謝謝 –

相關問題