Create a Graph and return it as an image on a nodejs server

0👍

You are looking for a library like chartjs-node-canvas or chartjs-node. These solutions render charts to PNG or other image formats.

Here’s what a chart render looks like in chartjs-node-canvas:

const { CanvasRenderService } = require('chartjs-node-canvas');

const width = 400; //px
const height = 400; //px
const canvasRenderService = new CanvasRenderService(width, height, (ChartJS) => { });

(async () => {
    const configuration = {
        // Add your Chart.js config here
    };
    const image = await canvasRenderService.renderToBuffer(configuration);
    const dataUrl = await canvasRenderService.renderToDataURL(configuration);
    const stream = canvasRenderService.renderToStream(configuration);
})();

You would still need to build your own web server. If you prefer a chart API that includes the rendering web server, you can use something like QuickChart, which is an open-source project of mine that wraps chartjs-node-canvas and renders your Chart.js charts.

In that case your code might look like this:

const QuickChart = require('quickchart-js');

const myChart = new QuickChart();
myChart
  .setConfig({
    type: 'bar',
    data: { labels: ['Hello world', 'Foo bar'], datasets: [{ label: 'Foo', data: [1, 2] }] },
  })
  .setWidth(800)
  .setHeight(400);

const chartImageUrl = myChart.getUrl();
// Download the url...

Leave a comment