[Chartjs]-How to add shadow effect on bar chart using ChartJs?

-1👍

import { Bar } from 'react-chartjs-2';

import {
  BarElement,
  CategoryScale,
  Chart as ChartJS,
  Legend,
  LinearScale,
  Title,
  Tooltip,
  TooltipItem,
} from 'chart.js';

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);

const shadowPlugin = [{
  id: 'shadow',
  beforeDraw: (chart: ChartJS<'bar', number[], unknown>) => {
    const { ctx } = chart;
    const _fill = ctx.fill;
    ctx.fill = function () {
      ctx.save();
      ctx.shadowColor = 'red';
      //ctx.shadowColor = 'rgba(12,77, 229, 0.2)';
      ctx.shadowBlur = 8;
      ctx.shadowOffsetX = 0;
      ctx.shadowOffsetY = 2;
      _fill.apply(this, arguments as any);
      ctx.restore();
    };
  },
}];

<Bar
  height={(BAR_THICKNESS + 28) * data.length + TICKS_PADDING}
  width={chartRefContainer?.current?.offsetWidth || undefined}
  ref={chartRef}
  options={options}
  data={dataWithGradient}
  plugins={shadowPlugin}
/>

result

Leave a comment