0👍
Edit: I see now you mentioned nchart
in the title; the solution below is based on standard chart.js, the latest version; it works well with node using node-canvas
– a similar setting to the answer to the older question you referenced.
nchart
is unfortunately bound to a (very) old version of chart.js
, which is not compatible to the plugin, nor to many other new features of chart.js
.
To run the code below with npm
, after you create a project with npm init
, save the code to index.js
, then npm install chart.js
, npm install chartjs-plugin-datalabels
, npm install canvas
.
Now there’s the plugin chartjs-plugin-datalabels
that works well to put labels on pie chart slices.
Here’s a minimal example that works:
const { Chart } = require("chart.js/auto");
const ChartDataLabels = require('chartjs-plugin-datalabels');
const { createCanvas } = require("canvas");
const fs = require("fs");
const width = 1200, height = 800;
const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");
new Chart(ctx, {
type: 'pie',
data: {
datasets: [{
data: [300, 50, 100],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 205, 86)'
]
}]
},
options:{
plugins: {
legend: {
display: false
},
datalabels: {
anchor: 'center',
color: '#000',
font: {size: '40px'},
backgroundColor: null,
},
}
},
plugins: [ChartDataLabels]
});
const buffer = canvas.toBuffer("image/png");
fs.writeFileSync("./image.png", buffer);
- Chartjs-How to customize horizontal bar in chart.js?
- Chartjs-How to I optimise these javscript options which is used multiple times on different chart.js graphs?
Source:stackexchange.com