How to make bars dashed in chart js?

๐Ÿ‘:0

You can create a custom chart type by extending Chart.BarController as explained here.

Please take a look at below runnable code and see how it works.

class DashedBorderBar extends Chart.BarController {
  draw() {
    super.draw(arguments);
    const ctx = this.chart.ctx;
    ctx.save();
    const dataset = this.chart.data.datasets[0];
    ctx.strokeStyle = dataset.dashedBorderColor;
    ctx.lineWidth = dataset.dashedBorderWidth;
    ctx.setLineDash(dataset.borderDash);    
    this.getMeta().data.forEach(d => {      
      ctx.strokeRect(d.x - d.width / 2, d.y, d.width, d.height + ctx.lineWidth);
    });
    ctx.restore();
  }
};
DashedBorderBar.id = 'dashedBorderBar';
DashedBorderBar.defaults = DashedBorderBar.defaults;
Chart.register(DashedBorderBar);

new Chart('myChart', {
  type: 'dashedBorderBar',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'Dataset',
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      data: [65, 59, 80, 81, 56, 45, 40],
      dashedBorderColor: 'blue',
      dashedBorderWidth: 3,
      borderDash: [10, 5]
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="myChart" height="120"></canvas>

Leave a comment