Chartjs-Animation of a graph of an equation javascript

0👍

To set max amount on your y Axes you can use the max property or suggestedMax if you want to make sure that if the data goes bigger the axis adapts. For the animation you can write custom logic as in the example underneath. I only dont know how to get the value its at on the click:

const labels = [1, 2, 3, 4, 5]

const totalDuration = 5000;
const delayBetweenPoints = totalDuration / labels.length;
const previousY = (ctx) => ctx.index === 0 ? ctx.chart.scales.y.getPixelForValue(100) : ctx.chart.getDatasetMeta(ctx.datasetIndex).data[ctx.index - 1].getProps(['y'], true).y;

var options = {
  type: 'line',
  data: {
    labels,
    datasets: [{
      label: '# of Votes',
      data: [],
      borderWidth: 1,
      function: function(x) {
        return x * x * x
      },
      borderColor: 'red',
      backgroundColor: 'red'
    }]
  },
  options: {
    scales: {
      y: {
        max: 250
      }
    },
    animation: {
      x: {
        type: 'number',
        easing: 'linear',
        duration: delayBetweenPoints,
        from: NaN, // the point is initially skipped
        delay(ctx) {
          if (ctx.type !== 'data' || ctx.xStarted) {
            return 0;
          }
          ctx.xStarted = true;
          return ctx.index * delayBetweenPoints;
        }
      },
      y: {
        type: 'number',
        easing: 'linear',
        duration: delayBetweenPoints,
        from: previousY,
        delay(ctx) {
          if (ctx.type !== 'data' || ctx.yStarted) {
            return 0;
          }
          ctx.yStarted = true;
          return ctx.index * delayBetweenPoints;
        }
      }
    }
  },
  plugins: [{
    id: 'data',
    beforeInit: function(chart) {
      var data = chart.config.data;
      for (var i = 0; i < data.datasets.length; i++) {
        for (var j = 0; j < data.labels.length; j++) {
          var fct = data.datasets[i].function,
            x = data.labels[j],
            y = fct(x);
          data.datasets[i].data.push(y);
        }
      }
    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
var chart = new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.1/chart.js" integrity="sha512-HJ+fjW1Hyzl79N1FHXTVgXGost+3N5d1i3rr6URACJItm5CjhEVy2UWlNNmFPHgX94k1RMrGACdmGgVi0vptrw==" crossorigin="anonymous"></script>
</body>

Leave a comment