【问题标题】:Display Chartjs tooltip values outside the canvas - multi line chart在画布外显示 Chartjs 工具提示值 - 多折线图
【发布时间】:2019-08-05 07:34:34
【问题描述】:

我正在尝试复制 NSE 证券交易所比较图,如 here 所示。

我正在使用Chartjs 2.0。我在图表中有 2 个折线图。

悬停在数据点上时,我想在画布外部的 div 中显示工具提示的 ylabel,(如上图右上角显示的变化值)

我发现 GRUNT 的代码很有帮助 Moving vertical line when hovering over the chart using chart.js

【问题讨论】:

  • 不清楚您的实际问题是什么或您已经编写了什么代码?

标签: chart.js chart.js2


【解决方案1】:

您可以使用Label Callback

document.getElementById('y-label').textContent = tooltipItem.yLabel;

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.scales['y-axis-0'].top,
        bottomY = this.chart.scales['y-axis-0'].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,
      callbacks: {
        label: function(tooltipItem, data) {
          var label = data.datasets[tooltipItem.datasetIndex].label || '';

          if (label) {
            label += ': ';
          }
          label += Math.round(tooltipItem.yLabel * 100) / 100;
          
          document.getElementById('y-label').textContent = tooltipItem.yLabel;
          return label;
        }
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>

<h4 id="y-label"> </h4>
<canvas id="ctx" height="200"></canvas>

【讨论】:

  • 感谢 User863 的回答。我的页面中有 2 个执行上下文 - 1. 具有状态对象的全局执行上下文 2. 图表的执行上下文。在 Chartjs 工具提示的标签回调中,有没有一种方法可以访问状态对象? .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
相关资源
最近更新 更多