【问题标题】:How to add shadow effect on bar chart using ChartJs?如何使用 ChartJs 在条形图上添加阴影效果?
【发布时间】:2022-11-04 21:14:18
【问题描述】:

我正在使用 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

【问题讨论】:

  • 默认情况下无法做到这一点,您需要为此创建一个自定义插件,版本 2.9 有一个,但它从未更新过 voe V3,因此您需要自己做:nagix.github.io/chartjs-plugin-style

标签: javascript html jquery css chart.js


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多