Chart.js 栏杆后面的笔划怎么画?

How to draw the stroke behind bars in Chart.js?

我在 Chart.JS 中写了一个自定义条形图,它在数据集上悬停时通过在其上绘制笔划来突出显示条形,问题是笔划是在条形图上绘制的,而我会使其类似于 'background color' 代替。

因为描边颜色不透明度设置为 0.05,所以条形是可见的,而如果我将其设置为 1,显然这些条形将不再可见。

代码

class CustomBar extends Chart.BarController {
    draw() {
        super.draw(arguments);
        if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
            const points = this.chart.tooltip._active[0];
            const ctx = this.chart.ctx;
            const x = points.element.x;
            const topY = points.element.y + 150;
            const width = points.element.width;
            const bottomY = 0;

            ctx.save();
            ctx.beginPath();
            ctx.moveTo(x, topY * 100);
            ctx.lineTo(x + width * 1.3, bottomY);
            ctx.lineWidth = width * 4.3;
            ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
            ctx.stroke();
            ctx.restore();
        }
    }
}

CustomBar.id = 'shadowBar';
CustomBar.defaults = Chart.BarController.defaults;

Chart.register(CustomBar);

为此您需要一个自定义插件,您可以在其中指定您希望它在绘制数据集之前绘制。你可以这样做:

Chart.register({
  id: 'barShadow',
  beforeDatasetsDraw: (chart, args, opts) => {
    const {
      ctx,
      tooltip,
      chartArea: {
        bottom
      }
    } = chart;
    
    if (!tooltip || !tooltip._active[0]) {
      return
    }
    
    const point = tooltip._active[0];
    const element = point.element;
    const x = element.x;
    const topY = -(element.height + 150);
    const width = element.width;
    const bottomY = 0;
    const xOffset = opts.xOffset || 0;
    const shadowColor = opts.color || 'rgba(0, 0, 0, 1)';

    ctx.save();
    ctx.beginPath();
    ctx.fillStyle = shadowColor;
    ctx.fillRect(x - (element.width / 2) + xOffset, bottom, width * 1.3 * 4.3, topY);
    ctx.restore();
  }
});

const options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: 'orange'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        backgroundColor: 'pink'
      }
    ]
  },
  options: {
    plugins: {
      barShadow: {
        xOffset: -10,
        color: 'red'
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>