[Chartjs]-How to draw the stroke behind bars in Chart.js?

2👍

You will need a custom plugin for this, in there you can specify that you want it to draw before the datasets are being drawn. You can do that like so:

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>

Leave a comment