[Chartjs]-Chart.JS Starting at 00:00am and ending at 23:59pm

1👍

You can use the min and max properties on the x axis like so:

const chart = new Chart('chartJSContainer', {
  type: "line",
  data: {
    labels: [
      new Date(1634847780000), // Last of previous day - Low Tide
      new Date(1634869320000), // High Tide 1
      new Date(1634891880000), // Low Tide 1
      new Date(1634913060000), // High Tide 2
      new Date(1634935560000), // Low Tide 2
      new Date(1634955720000), // First of next day - High Tide
    ],
    datasets: [{
      label: "My First dataset",
      data: [0.7, 5.8, 0.8, 5.8, 0.8, 5.1], // Meters above sea
      tension: 0.5,
      backgroundColor: "#000000",
      fill: {
        target: "origin",
      },
    }, ],
  },
  options: {
    interaction: {
      mode: "point",
    },
    hover: {
      mode: "point",
    },
    onHover: (e) => {
      const canvasPosition = getRelativePosition(e, chart);

      // Substitute the appropriate scale IDs
      const dataX = chart.scales.x.getValueForPixel(canvasPosition.x);
      const dataY = chart.scales.y.getValueForPixel(canvasPosition.y);
      console.log(dataY);
    },
    plugins: {
      tooltip: {
        enabled: true,
      },
      legend: {
        display: false,
      },
    },
    scales: {
      xAxis: {
        type: "time",
        min: new Date(1634853600000), // Should calculate this dynamic, not best way but can use: new Date().setHours(0,0,0,0)
        max: new Date(1634939999000), // Should calculate this dynamic, not best way but can use: new Date().setHours(23,59,59)
        time: {
          unit: "hour",
          displayFormats: {
            hour: "HH:mm",
          },

          // minUnit: moment(1634860800000).format("HH:mm"),
        },
      },
      yAxis: {
        ticks: {
          callback: function(value, index, values) {
            return value + "m";
          },
        },
      },
    },
  },
});
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
</body>

Leave a comment