andreaferretti / paths-js

Generate SVG paths for geometric shapes :bar_chart:
http://andreaferretti.github.io/paths-js-react-demo/
Apache License 2.0
1.71k stars 84 forks source link

How can we use this library on server side (Node JS)? #42

Closed venkatesh-tr closed 7 years ago

venkatesh-tr commented 7 years ago

I do have a requirement of sending an email based on a template (using handlebars) which should show a chart in it. I am planning to use Path.js as the main README says that I can use this library on server side too. But I am clueless about how can I use it on server side. Can you provide some guidance or route to get it done?

andreaferretti commented 7 years ago

First of all, you can depend on the paths-js package on NPM, then import a module - say Pie - with

var Pie = require('paths-js/pie');

Then you will have some data, such as

var countries = [
  { name: 'Italy', population: 59859996 },
  { name: 'Mexico', population: 118395054 },
  { name: 'France', population: 65806000 },
  { name: 'Argentina', population: 40117096 },
  { name: 'Japan', population: 127290000 }
];

Then you generate the chart like this (here we use compute to include additional information in the generated object, in this case the color)

var palette = [...];
var chart = Pie({
    center: [0,0],
    r: 60,
    R: 140,
    data: countries,
    accessor: function(c) { return c.population; },
    compute: {
      color: function(item, i) { return palette[i]; }
    }
});

What you get is a simple javascript object containing the geometric information you need to draw the chart. Then it's up to you to write a handlebar template which takes this geometric information and turns it into an SVG. I don't remember handlebars very well, but it should be something like

<svg width="375" height="400">
  <g transform="translate(200, 200)">
    {{#each chart.curves }}
      <path d="{{ sector.path }}" fill={{ color }} />
    {{/each}}
  </g>
</svg>

Please note that I have not tried the above code, so there may be typos and all, but more or less it should be ok. If you have more specific problems, let me know