score:0

your code for getting the right pixel is incorrect if you change it to this it will work: xaxis.getpixelforvalue(chart.config.data.datasets[0].data[index].x)

live example:

var originallinedraw = chart.controllers.line.prototype.draw;
chart.helpers.extend(chart.controllers.line.prototype, {
  draw: function() {
    originallinedraw.apply(this, arguments);
    var chart = this.chart;
    var ctx = chart.chart.ctx;
    var index = chart.config.data.lineatindex;
    if (index) {
      var xaxis = chart.scales['x-axis-0'];
      var yaxis = chart.scales['y-axis-0'];


      ctx.save();
      ctx.beginpath();
      ctx.moveto(xaxis.getpixelforvalue(chart.config.data.datasets[0].data[index].x), yaxis.top);
      ctx.strokestyle = 'red';
      ctx.lineto(xaxis.getpixelforvalue(chart.config.data.datasets[0].data[index].x), yaxis.bottom);
      ctx.stroke();
      ctx.restore();
    }
  }
});
var config = {
  type: 'line',
  data: {
    datasets: [{
      label: "my first dataset",
      data: [{
          x: moment(1591900200000),
          y: 1936.88
        }, {
          x: moment(1592159400000),
          y: 379.38
        },
        {
          x: moment(1592245800000),
          y: 2495.94
        }, {
          x: moment(1592332200000),
          y: -938.44
        },
        {
          x: moment(1592418600000),
          y: -1697.19
        }, {
          x: moment(1592505000000),
          y: -1058.44
        },
        {
          x: moment(1592764200000),
          y: 439.38
        }, {
          x: moment(1592850600000),
          y: 758.75
        }
      ],
      fill: false,
      backgroundcolor: 'blue',
      bordercolor: 'blue',
    }],
    lineatindex: 2
  },
  options: {
    scales: {
      xaxes: [{
        type: 'time'
      }]
    }
  }
};
new chart('chartjscontainer', config);
<body>
  <canvas id="chartjscontainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.9.4/chart.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-moment/1.0.0/chartjs-adapter-moment.min.js"></script>
</body>


Related Query

More Query from same tag