2013-01-31 120 views
9

我有用D3 JavaScript庫生成的圖表,我需要將這些圖表保存爲PNG或SVG文件。保存<svg>將HTML5轉換爲PNG或圖像

是否有一些圖書館能夠完成這項工作?

我發現這個https://github.com/sampumon/SVG.toDataURL但在Firefox控制檯不工作對我的HTML5, 我得到這個錯誤:

NS_ERROR_NOT_AVAILABLE:組件不可用 [Interrompi每questo errore]

ctx.drawImage( img,0,0);

+2

下面是如何使用Chrome進行操作的示例:http://bl.ocks.org/3831266 – Duopixel

+0

謝謝!這是工作......但是當我嘗試在Illustrator中打開文件時,它要求我驗證該文件。我有這樣的消息:此svg​​無效。打開之前進行驗證。 –

+0

查找XML驗證程序並確保它是有效的XML。如果一切正常,然後將代碼發佈到您的問題中,我可以幫助您找到導致Illustrator跳閘的錯誤。 – Duopixel

回答

1

服務器端腳本方法

這裏有一個簡單的方法來保存SVG元素爲PNG(雖然它使用的服務器端腳本,這可能是由你所期望的不同): 結帳this page。如作者所記錄的,客戶端提取svg元素(使用XMLSerializer.serializeToString)並將其發送到服務器;服務器將其轉換爲png並將其發送回客戶端。服務器可以使用任何方便的程序(在這種情況下rsvg-convert)。

Canvg庫

你可以使用這個庫來做到這一點在客戶端(check it out!)

canvg is a SVG parser and renderer. It takes a URL to a SVG file or the text of an SVG file, parses it in JavaScript, and renders the result on a Canvas element

使用方法如下:

//load a svg snippet in the canvas with id = 'drawingArea' 
canvg(document.getElementById('drawingArea'), '<svg>... </svg>') 

然後你可以使用toDataURL方法: document.getElementById('drawingArea').toDataURL('image/png');

1

Ex充足從developer.mozilla.org演示如何使用畫布元素將svg導出到png。

var canvas = document.getElementById('canvas'); 
var ctx = canvas.getContext('2d'); 

var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' + 
      '<foreignObject width="100%" height="100%">' + 
      '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' + 
      '<em>I</em> like ' + 
      '<span style="color:white; text-shadow:0 0 2px blue;">' + 
      'cheese</span>' + 
      '</div>' + 
      '</foreignObject>' + 
      '</svg>'; 

var DOMURL = window.URL || window.webkitURL || window; 

var img = new Image(); 
var svg = new Blob([data], {type: 'image/svg+xml'}); 
var url = DOMURL.createObjectURL(svg); 

img.onload = function() { 
    ctx.drawImage(img, 0, 0); 
    DOMURL.revokeObjectURL(url); 
    var png_img = canvas.toDataURL("image/png"); 
} 

img.src = url;