Home > other >  Add a gradient background to react-chartjs-2
Add a gradient background to react-chartjs-2

Time:07-11

I am currently trying to add a gradient background with a slight transparency to a radar graph inside a react component. I have only been able to find solutions for this problem by referencing a chartjs canvas within an html file, but no solutions via a react component in a tsx/jsx file.

Desired Result I am looking for, and the Current Result

The code below is used to achieve the current result.

import { Chart } from 'react-chartjs-2';
import { Chart as ChartJS, LineController, LineElement, PointElement, LinearScale, Title, Filler, RadialLinearScale } from 'chart.js';

ChartJS.register(LineController, RadialLinearScale, LineElement, PointElement, LinearScale, Filler, Title);

const labels = ['Thing 1', 'Thing 2', 'Thing 3', 'Thing 4', 'Thing 5', 'Thing 6'];
const chartData = [5, 3, 4, 5, 2, 4];

const data = {
  labels: labels,
  datasets: [
    {
      data: chartData, 
      fill: true,
      backgroundColor: 'pink',
      borderColor: 'transparent',
      pointBorderColor: 'transparent',
      pointBackgroundColor: 'transparent',
    },
  ],
};

const options = {
  scales: {
    r: {
      grid: {
        lineWidth: 2,
      },
      angleLines: {
        lineWidth: 2,
      },
      gridLines: {
        display: false
      },
      ticks: {
        display: false,
        maxTicksLimit: 1
      },
    }
  }
}

const RadarGraph = () => {
    
  return (
      <Chart type="radar" data={data} options={options}/>
  )
}

export default RadarGraph;

CodePudding user response:

You will need to use a scriptable function for the backgroundColor which contains the chart which contains the context like so:

const data = {
  labels: labels,
  datasets: [
    {
      data: chartData, 
      fill: true,
      backgroundColor: ({chart: {ctx}}) => {
        const bg = ctx.createLinearGradient(paramters);
        // More config for your gradient
        return bg;
      }
    },
  ],
};
  • Related