[Chartjs]-How to include adapters and plugins with ChartJS

1๐Ÿ‘

โœ…

As stated in the documentation and migration guide since chart.js version 3 you will need to include a date adapter yourself.

Example:

var default_series = [1, 2, 3, 4, 5];
var default_time_series = [new Date()];

for (let i = 1; i < 5; i++) {
  var tempDay = new Date(default_time_series[i - 1]);
  tempDay.setDate(tempDay.getDate() + 1);
  default_time_series.push(new Date(tempDay.valueOf()));
}

const default_chart_dataset = {
  data: [],
  label: 'Default',
  borderColor: '#000000',
  fill: false,
  hidden: false,
  spanGaps: false,
  pointRadius: 0
};

var chart_data = {
  type: 'line',
  data: {
    labels: [],
    datasets: []
  },
  options: {
    title: {
      display: true,
      text: "A Chart"
    },
    scales: {
      x: {
        type: "time",
        time: {
          // unit: 'day',
          // tooltipFormat: 'MMM DD',
          displayFormats: {
            day: 'MMM DD YY'
          }
        }
      }
    },
    plugins: {
      zoom: {
        pan: {
          enabled: true,
          mode: 'x'
        },
        zoom: {
          wheel: {
            enabled: true
          },
          pinch: {
            enabled: true
          },
          mode: 'x'
        }
      }
    }
  }
};

var main_chart = new Chart(document.getElementById('a-chart').getContext('2d'), chart_data);
main_chart.data.datasets.push({ ...default_chart_dataset
});
main_chart.data.datasets[0].data = [...default_series];
main_chart.data.labels = [...default_time_series];
main_chart.update();
<html lang="en">

<body>
  <canvas id="a-chart" class="a-graph" width="850" height="350"></canvas>

  <script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.0/dist/chart.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8/hammer.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@1.1.1/dist/chartjs-plugin-zoom.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-moment/1.0.0/chartjs-adapter-moment.js"></script>
</body>

</html>

Leave a comment