2013-04-17 112 views
26

我正在處理客戶端/ javascript功能以將現有D3-SVG圖保存或轉換爲文件。 我搜了很多,發現一些建議,主要使用canvas.toDataURL()如何將d3.js圖轉換/保存爲pdf/jpeg

我沒有<canvas>在我的網頁,並且不使用:d3.select("body").append("svg").... 我也試着到SVG追加到<canvas>但沒有任何反應。

能否請你幫我解決這個異常:

Uncaught TypeError: Object #<SVGSVGElement> has no method 'toDataURL' 

謝謝

+0

對於在瀏覽器中轉換爲PNG,請檢查http://stackoverflow.com/questions/3975499/convert-svg-to-image-jpeg-png-etc-in-the-browser – widged

+0

如果它不需要在運行時,像casperjs這樣的工具讓你截取頁面中的任何元素的截圖http://casperjs.org/api.html#casper.captureSelector – widged

+0

對於pdf導出,請參閱http://stackoverflow.com/questions/3360641 /如何對插入-A-SVG文件-IN-A-PDF文檔。 – widged

回答

19

要顯示一個畫面內的SVG,你首先必須使用一個解析器/渲染器工具將其轉換如http://code.google.com/p/canvg/

(改編自代碼:Convert SVG to image (JPEG, PNG, etc.) in the browser,未測試)

// the canvg call that takes the svg xml and converts it to a canvas 
canvg('canvas', $("#my-svg").html()); 

// the canvas calls to output a png 
var canvas = document.getElementById("canvas"); 
var img = canvas.toDataURL("image/png"); 
+1

第一行不起作用,因爲1. canvg等待URL,而不是實際的XML數據,2. $('svg')。html()也不能用 - 你需要innerSVG JS庫才能訪問內部SVG XML。 – WASD42

+0

'canvg(document.getElementById('drawingArea'),' ...')'作爲用法https://github.com/gabelerner/canvg給出。將$('svg')。html()'更改爲'$(「#my-svg」)。html()'。 – widged

+1

一旦你有img,你如何觸發它的下載? – rjurney

3

正如在這個問題Convert SVG to image (JPEG, PNG, etc.) in the browser

此評論所指出的@Premasagar如果borwser支持SVG和畫布,你可以使用這種技術https://svgopen.org/2010/papers/62-From_SVG_to_Canvas_and_Back/index.html

function importSVG(sourceSVG, targetCanvas) { 
    // https://developer.mozilla.org/en/XMLSerializer 
    svg_xml = (new XMLSerializer()).serializeToString(sourceSVG); 
    var ctx = targetCanvas.getContext('2d'); 

    // this is just a JavaScript (HTML) image 
    var img = new Image(); 
    // http://en.wikipedia.org/wiki/SVG#Native_support 
    // https://developer.mozilla.org/en/DOM/window.btoa 
    img.src = "data:image/svg+xml;base64," + btoa(svg_xml); 

    img.onload = function() { 
     // after this, Canvas’ origin-clean is DIRTY 
     ctx.drawImage(img, 0, 0); 
    } 
} 
6

剛擡起頭,我把這個概念到一個小的JavaScript庫:https://github.com/krunkosaurus/simg

它只是將任何SVG轉換爲圖像換出或觸發下載。從這裏採取的想法:http://techslides.com/save-svg-as-an-image/

+0

即時通訊試圖讓你的js庫,但不工作。來自techslides的代碼確實有效,雖然不是Firefox 33.0 我注意到的一件事是您的代碼將a.href引用到img src,而不是canvas數據URL。有任何想法嗎? – Sebastian

+0

此外,即時使用從DC.js和png文件的lineChart看起來像CSS樣式沒有應用,即使我粘貼在html中的所有dc.css。 – Sebastian

+0

@sebastian:在收到一些pull請求後,我繼續前進,並用文檔和更多功能更新了代碼庫。 –

1

上面的Mauvis Ledford創建並建議的Simg庫很適合允許我使用Dimple創建的svg圖表下載。

但是我確實需要更改代碼的一個方面才能使其工作。如果將「svg.setAttribute(..)」更改爲「svg [0] .setAttribute」,它將緩解「setAttribute(..)」不在「toString一個函數「錯誤。類似地,在return語句中需要做同樣的事情,在svg(第39行)之後附加「[0]」。

我還必須手動編輯toCanvas()原型中的「canvas.width」和「canvas.height」(第48行的49)賦值,以便使下載的圖像的尺寸更加正確(這是以前只是在圖表的左上角下載一個靜態的300x150正方形)。