chart.jsreact-chartjs

React chartjs: background gradient not appearing


Trying to create a gradient background for my Line chart. The solution I tried to implement is not working. See screenshot: current chart

I implemented canvas's createLinearGradient() to no avail. What else could I be doing wrong? Edit: I added all my imports, including the Filler. This way it still doesn't work.

import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
  ScriptableContext,
} from "chart.js";

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
);

function Linechart() {
  const labels = ["January", "February", "March", "April", "May", "June"];

  const dataLineChart = {
    labels: labels,
    datasets: [
      {
        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;
        },
        label: "UST",
        fill: "start",
        borderColor: "#8E95DF",
        data: [0, 10, 5, 2, 20, 30, 45],
      },
    ],
  };

  const configLineChart = {
    type: "line",
    dataLineChart,
    elements: {
      line: {
        tension: 0.35,
      },
    },
    plugins: {
      filler: {
        propagate: false,
      },
    },
  };

  return (
    <div>
      <div className="px-5 py-3">Fund Profits</div>
      <Line data={dataLineChart} options={configLineChart}></Line>
    </div>
  );
}

export default Linechart;

Edit: When changing this const gradient = ctx.createLinearGradient(0, 0, 0, 200); to const gradient = ctx.createLinearGradient(0, 0, 0, 500); my gradient becomes visible. Can someone explain how that value works?


Solution

  • The 200 and 500 refers to pixel x/y positionings within the graph. It lets you decide at which axis location you want the gradient to start/stop. Here are the docs that tell you the meanings behind each value:

    https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient

    I have my linear gradient going from color on the top to transparent on the bottom. Here's my implementation:

    const gradient = context.chart.ctx.createLinearGradient(0, 0, 0, context.chart.chartArea.height);
    

    In this example, I used my context.chart.chartArea.height to tell me the height of the canvas and I made it connect tot he top so that the gradient was over the whole background (ie super high values would have a bright color whereas low ones would be transparent on the fill).