[Chartjs]-How do i create this chart in ChartJS? In NEXTjs with TSX

1πŸ‘

βœ…

To implement a chart as you posted, you need a custom plugin.

Here a sample:

const labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const rndMinMax = (min, max) => Math.floor(Math.random() * (max - min)) + min;
const getData = () => {
  const start = rndMinMax(0, 12);
  const end = rndMinMax(start, 24);
  return [start, end];
}

const plugin = {
  id: 'barShadowing',
  beforeDatasetDraw(chart, args, options) {
    const ctx = chart.ctx
    const meta = args.meta;
    const yScale = meta.yScale;
    const {top, bottom} = yScale;
    ctx.save();
    meta.data.forEach(function(element, i) {
      const {x, width, options} = element;
      const shadow = {
        x: x - (width / 2),
        w: width,
        y: top,
        h: bottom - top,
        radius: Chart.helpers.toTRBLCorners(options.borderRadius)
      };
      ctx.beginPath();
      ctx.fillStyle = 'rgb(196, 219, 239)';
      Chart.helpers.addRoundedRectPath(ctx, shadow);
      ctx.fill();
    });
    ctx.restore();
  }
}

const config = {
  type: 'bar',
  plugins: [plugin],
  data: {
    labels,
    datasets: [{
      label: "My First dataset",
      data: labels.map(() => getData()),
      categoryPercentage: 0.25,
      backgroundColor: 'rgb(17, 116, 236)',
      borderRadius: 8,
      borderSkipped: false
    }]
  },
  options: {
    plugins: {
      legend: false
    },
    scales: {
      x: {
        grid: {
          display: false
        },
        ticks: {
          font: {
            size: 16
          }
        }
      },
      y: {
        min: 0,
        max: 24,
        ticks: {
          font: {
            size: 16
          },
          stepSize: 4,
          callback: (value) => value + ':00'
        }
      }
    }
  }
};

const ctx = document.getElementById("myChart").getContext("2d");
const myChart = new Chart(ctx, config);
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://npmcdn.com/chart.js@latest/dist/chart.umd.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

Leave a comment