Chartjs-How do I create a chart and write it to a png file?

0👍

You do need a canvas for chart.js to work. Fortunately, there are some projects that can provide a virtual canvas in node. I use node-canvas; see also this blog post.

It is a little tricky to set the background color, but chart.js docs provide us with a solution.

Thus, after npm installing canvas (you already have installed chart.js), your code can be transformed to:

const { Chart } = require("chart.js/auto");

//from https://blog.logrocket.com/creating-saving-images-node-canvas/
const { createCanvas } = require("canvas");
const fs = require("fs");

const width = 1200, height = 800;

const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");

// not working
// ctx.fillStyle = "#ffffff";
// ctx.fillRect(0, 0, canvas.width, canv\as.height);

// from https://www.chartjs.org/docs/latest/configuration/canvas-background.html
const plugin = {
    id: 'customCanvasBackgroundImage',
    beforeDraw: (chart) => {
        const ctx = chart.ctx;
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }
};

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: [1, 2, 3, 4, 5],
        datasets: [{
            label: 'data',
            data: [[-3, 5], [2, 10], [1, 3], [-4, -1], [4, 8]],
            backgroundColor: 'lightblue'
        }]
    },
    options: {
        indexAxis: 'y',
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Horizontal Floating Bars'
        }
    },
    plugins: [plugin]
});

const buffer = canvas.toBuffer("image/png");
fs.writeFileSync("./image.png", buffer);

Leave a comment