将SVG代码转换为node.js中的PNG数据URI

我想将简单的dynamicsvg片段转换为服务器上的PNG数据URI。 像这样的东西:

var svg = '<svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>' console.log('<img src="data:image/png;base64,'+toPng(svg, 100, 100)+'">') 

我看过使用imagemagick和一些phantomJS变体的例子,但是我正在寻找node.js中的dynamic解决scheme,最好没有I / O。

       

网上收集的解决方案 "将SVG代码转换为node.js中的PNG数据URI"

这里有一个使用Fabric.js的方法 :

第1步:安装Cairo和node-canvas :
(我在Ubuntu 14.04上,其他操作系统的说明可以在这里find。)

 sudo apt-get update sudo apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++ sudo npm install canvas 

第2步:安装Fabric.js:

 sudo npm install fabric 

第3步:使用node运行以下JavaScript:

 var fabric = require('fabric').fabric; var canvas = new fabric.createCanvasForNode(100, 100); var svgStr = '<svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>'; fabric.loadSVGFromString(svgStr, function(objects, options) { var obj = new fabric.PathGroup(objects, options); canvas.add(obj); console.log('<img src="' + canvas.toDataURL() + '" />'); }); 

结果:
(在节点v0.10.25上运行)

 <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAABmJLR0QA/wD/AP+gvaeTAAAHD0lEQVR4nO2dW2wVRRjHf6XSFgq1BUEoIiCXKih4jYmGxAR8MBa5RQloDD7wAA/og8EHfdAXEowm8oCGJxQviXhJjKkEUSgKeIkoohYLCCggt0JbwBah9vNhdnt2z57LbDl7dujOL/nSmZOzZ2e+/+52d+abb8FisVgsFovFYrFYLImmJO4GaDIAmAZMBCY5f8cCA4FKoBrVl26gHfgH6AAOAfsd2wfsATqL2/RwmCrINcB04AHH7gXKC/C7/wLfAo3AVmAH0FWA3+2TlAAzgfVAGyBFsFZnfzMx5OA0oRGlwALgOWBqpi+UAFOA24DJQJ1jg4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