Hello I'm trying to use chart.js to create charts however I have found it hard to find out how to create graphs in my node js program, it requires a context but as it's local I'm not sure what to put in here as it's not meant to be a site and it will also not be.
I would like to create a graph and just put it out as a png is there a way to do this?
I tried
const { Chart } = require("chart.js/auto");
let ctx = null
let crt = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: [1, 2, 3, 4, 5],
datasets: [{
label: 'data',
data: [[-3, 5], [2, 10], [1, 3], [-4, -1], [4, 8]],
backgroundColor: 'lightblue'
}]
},
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Horizontal Floating Bars'
}
}
});```
But have not had any results from this as I got an error. Can someone please help me?
CodePudding user response:
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);