[Chartjs]-React-chartjs-2 gradient fill error on canvas context

16👍

This is because you dont pass any canvas to the data function when you call it in

<Line data={data} options={options} />

But the canvas is also not availabale here. If you want to make a custom gradient you will need to apply a scriptable option for the backgroundColor like so:

const data = () => {
  return {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    datasets: [{
      label: "First dataset",
      data: [33, 53, 85, 41, 44, 65],
      fill: "start",
      backgroundColor: (context: ScriptableContext<"line">) => {
        const ctx = context.chart.ctx;
        const gradient = ctx.createLinearGradient(0, 0, 0, 200);
        gradient.addColorStop(0, "rgba(250,174,50,1)");
        gradient.addColorStop(1, "rgba(250,174,50,0)");
        return gradient;
      },
      borderColor: "rgba(75,192,192,1)"
    }]
  };
};

Also make sure to call the function in your data field so your html becomes this:

<Line data={data()} options={options} />

Working Codesandbox: https://codesandbox.io/s/interesting-faraday-204ugi?file=/src/LineChartGradient.tsx

-1👍

so it’s look that there is a lot of errors with your code , i’m trying to help by solving the second problem , data should be json not a function so to solve this you should to execute the function before pass it like this :

<Line data={data()} options={options} />
  
  export default function Chart(){
    return (
    <div>
    {
    /****
    pass data() not data
    ****/
    }
      <Line data={data()} options={options} />
    </div>
  );
  }

Leave a comment