# 从 Node.js 使用

¥Using from Node.js

你可以在 Node.js 中使用 Chart.js,借助 NPM 包(例如 node-canvas (opens new window)skia-canvas (opens new window))在服务器端生成图表。

¥You can use Chart.js in Node.js for server-side generation of plots with help from an NPM package such as node-canvas (opens new window) or skia-canvas (opens new window).

示例用法:

¥Sample usage:

import {CategoryScale, Chart, LinearScale, LineController, LineElement, PointElement} from 'chart.js';
import {Canvas} from 'skia-canvas';
import fsp from 'node:fs/promises';
Chart.register([
  CategoryScale,
  LineController,
  LineElement,
  LinearScale,
  PointElement
]);
const canvas = new Canvas(400, 300);
const chart = new Chart(
  canvas, // TypeScript needs "as any" here
  {
    type: 'line',
    data: {
      labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
      datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'red'
      }]
    }
  }
);
const pngBuffer = await canvas.toBuffer('png', {matte: 'white'});
await fsp.writeFile('output.png', pngBuffer);
chart.destroy();