Convert SVG code into PNG data URI in node.js

前端 未结 2 1415
一向
一向 2021-02-07 14:48

I’d like to convert a simple dynamic svg snippet into a PNG data URI on the server. Something like this:

var svg = \'<         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 15:40

    Here's a way to do it using Fabric.js:

    Step 1: Install Cairo and node-canvas:
    (I'm on Ubuntu 14.04, instructions for other OSes can be found here.)

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

    Step 2: Install Fabric.js:

    sudo npm install fabric
    

    Step 3: Run the following JavaScript with node:

    var fabric = require('fabric').fabric;
    var canvas = new fabric.createCanvasForNode(100, 100);
    var svgStr = '';
    
    fabric.loadSVGFromString(svgStr, function(objects, options) {
      var obj = new fabric.PathGroup(objects, options);
      canvas.add(obj);            
      console.log('');
    });
    

    Result:
    (Ran on node v0.10.25.)

    Special thanks to this question for the fabric.loadSVGFromString example.

提交回复
热议问题