SeanSobey / ChartjsNodeCanvas

A node renderer for Chart.js using canvas.
MIT License
228 stars 70 forks source link

Cannot get ChartCallback to work - importing ChartJS not working #133

Closed MartinHatchUK closed 1 year ago

MartinHatchUK commented 1 year ago

So I'm trying to render a basic chart with a gradient background. If I remove the callback then everything works just fine. But as soon as I try to include the callback I get errors relating to ChartJS not being able to import "Chart"

Am I doing something wrong below?

Here is my code:

import Chart from 'chart.js/auto';
import { ChartJSNodeCanvas } from "chartjs-node-canvas";

const width = 1024; // px
const height = 768; // px

// const { Chart } = await import("chart.js")

const chartCallback = (Chart) => {
  Chart.plugins.register({
    beforeDraw: (chartInstance) => {
      const { chart } = chartInstance
      const { ctx } = chart

      const gradientBackground = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
      grd.addColorStop(0, "#595959");
      grd.addColorStop(1, "#272727");

      chart.data.datasets[0].backgroundColor = gradientBackground;
    },
     })
  }

const backgroundColour = "white"; // Uses https://www.w3schools.com/tags/canvas_fillstyle.asp
const chartJSNodeCanvas = new ChartJSNodeCanvas({
  width,
  height,
  backgroundColour,
  chartCallback: chartCallback
});

export default chartJSNodeCanvas;
MartinHatchUK commented 1 year ago

Was using the wrong method. This worked a charm

import { ChartJSNodeCanvas } from "chartjs-node-canvas";

const width = 1024; // px
const height = 768; // px
const backgroundColour = "transparent"; 

const chartJSNodeCanvas = new ChartJSNodeCanvas({
  width,
  height,
  backgroundColour,
  chartCallback: (ChartJS) => {

    try {
      ChartJS.defaults.global.defaultFontColor = "#fff";
    }
    catch {}

    ChartJS.register({
      id: 'my_background_color',
      beforeDraw: (chart, _options) => {
        const ctx = chart.ctx;
        ctx.save();

        const centerX = 1024/2; // half width
        const centerY = 768/2; // half height
        const r = 550; // radius of gradient

        const grd = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, r);
        grd.addColorStop(0, "#595959");
        grd.addColorStop(1, "#272727");

        ctx.fillStyle = grd;
        ctx.fillRect(0, 0, width, height);
        ctx.restore();
      }
    })
  }});

export default chartJSNodeCanvas;