Moving vertical line when hovering over the chart using chart.js

后端 未结 2 2004
你的背包
你的背包 2020-11-30 07:02

I\'ve been trying to add a vertical line that shows up with a tooltip when hovering over the chart. But I\'m using chart.js 2.6 and the syntax from 1.x seems to be outdated.

2条回答
  •  星月不相逢
    2020-11-30 07:10

    Solution for ChartJS 2.6.0

    ꜱᴄʀɪᴘᴛ (ᴇxᴛᴇɴᴅɪɴɢ ʟɪɴᴇ ᴄʜᴀʀᴛ)

    Chart.defaults.LineWithLine = Chart.defaults.line;
    Chart.controllers.LineWithLine = Chart.controllers.line.extend({
       draw: function(ease) {
          Chart.controllers.line.prototype.draw.call(this, ease);
    
          if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
             var activePoint = this.chart.tooltip._active[0],
                 ctx = this.chart.ctx,
                 x = activePoint.tooltipPosition().x,
                 topY = this.chart.legend.bottom,
                 bottomY = this.chart.chartArea.bottom;
    
             // draw line
             ctx.save();
             ctx.beginPath();
             ctx.moveTo(x, topY);
             ctx.lineTo(x, bottomY);
             ctx.lineWidth = 2;
             ctx.strokeStyle = '#07C';
             ctx.stroke();
             ctx.restore();
          }
       }
    });
    

    You would also need to set intersect: false for tooltips.

    ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

    Chart.defaults.LineWithLine = Chart.defaults.line;
    Chart.controllers.LineWithLine = Chart.controllers.line.extend({
       draw: function(ease) {
          Chart.controllers.line.prototype.draw.call(this, ease);
    
          if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
             var activePoint = this.chart.tooltip._active[0],
                 ctx = this.chart.ctx,
                 x = activePoint.tooltipPosition().x,
                 topY = this.chart.legend.bottom,
                 bottomY = this.chart.chartArea.bottom;
    
             // draw line
             ctx.save();
             ctx.beginPath();
             ctx.moveTo(x, topY);
             ctx.lineTo(x, bottomY);
             ctx.lineWidth = 2;
             ctx.strokeStyle = '#07C';
             ctx.stroke();
             ctx.restore();
          }
       }
    });
    
    var chart = new Chart(ctx, {
       type: 'LineWithLine',
       data: {
          labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
          datasets: [{
             label: 'Statistics',
             data: [3, 1, 2, 5, 4, 7, 6],
             backgroundColor: 'rgba(0, 119, 204, 0.8)',
             borderColor: 'rgba(0, 119, 204, 0.3)',
             fill: false
          }]
       },
       options: {
          responsive: false,
          tooltips: {
             intersect: false
          },
          scales: {
             yAxes: [{
                ticks: {
                   beginAtZero: true
                }
             }]
          }
       }
    });
    
    

提交回复
热议问题