Skip to content

Server-side rendering ​

Chart.js draws on any object that behaves like a canvas. In Node, the canvas package provides one, and a histogram renders like any other chart. Turn off animation and responsiveness, which need a browser.

js
import {writeFile} from 'node:fs/promises';
import {createCanvas} from 'canvas';
import {Chart, registerables} from 'chart.js';
import {HistogramController, HistogramElement} from 'chartjs-chart-histogram';

Chart.register(...registerables, HistogramController, HistogramElement);

const canvas = createCanvas(800, 400);
const chart = new Chart(canvas, {
  type: 'histogram',
  data: {datasets: [{label: 'Values', data: values, bins: 'auto'}]},
  options: {animation: false, responsive: false, events: []}
});

await writeFile('histogram.png', canvas.toBuffer('image/png'));
chart.destroy();

chart.toBase64Image() also works, and gives a data URL.

If you only need the numbers, not an image, use computeBins from chartjs-chart-histogram/core: it needs neither Chart.js nor a canvas.

Released under the MIT License.