如何使用ChartJs在条形图上添加阴影效果?

nhhxz33t  于 2022-11-23  发布在  Chart.js
关注(0)|答案(1)|浏览(174)

我正在使用chartjs 3.9构建一个条形图。我试图在条形图上获得一个阴影效果,如下所示:

我在文档中找不到如何执行此操作。有人能帮助我吗?
这是我的数据集:

datasets: [
        {
            label: 'SLP',
            data: [23000, 46000, 40000, 41000, 39000, 25000, 45000, 40500, 41000],
            backgroundColor: gradientBg21,
            borderRadius: 9,
            categoryPercentage: 0.8,
            barPercentage: 0.8
        },
        {
            label: 'AXS',
            data: [19000, 22000, 19000, 42000, 39500, 18000, 22000, 18000, 42000],
            backgroundColor: gradientBg31,
            borderRadius: 9,
            categoryPercentage: 0.8,
            barPercentage: 0.8
        }
    ]

这是我的图表:JsFiddle

r8xiu3jd

r8xiu3jd1#

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

相关问题