如何向Chart.js添加垂直交互式指南行

时间:2016-10-21 22:43:39

标签: javascript chart.js

我正在尝试使用Chart.js构建一个相当简单的折线图,但是当我将鼠标悬停在一个点上时,我需要它有一条垂直的引导线与tooltop一起显示。我想要一些与http://nvd3.org/examples/line.html非常相似但使用Chart.js的东西。

这是我想要的一个例子,我从各种例子拼凑而成。请注意,当您将鼠标悬停在某个点上时,该线会消失。

var ctx = document.getElementById("myChart");

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    datasets: [{
      fill: true,
      label: 'You',
      backgroundColor: 'rgba(0,170,238, 0.5)',
      data: [8, 16, 30, 15, 12, 4]
    }, {
      fill: true,
      label: 'Others',
      backgroundColor: 'rgba(153,170,238, 0.5)',
      data: [5, 4, 3, 5, 2, 3]
    }]
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      mode: 'x-axis',
      backgroundColor: '#ffffe0',
      bodyFontColor: '#000',
      bodySpacing: 7,
      multiKeyBackground: '#ffffe0',
      titleFontColor: '#000',
      titleMarginBottom: 5,
      xPadding: 10,
      yPadding: 10
    },
    scales: {
      xAxes: [{
        display: false
      }],
      yAxes: [{
        display: false
      }]
    }
  }
});

// Hook into main event handler
var parentEventHandler = Chart.Controller.prototype.eventHandler;
Chart.Controller.prototype.eventHandler = function(e) {
  console.log(e);
  var ret = parentEventHandler.apply(this, arguments);
  this.clear();
  this.draw();
  // Draw the vertical line here
  var eventPosition = Chart.helpers.getRelativePosition(arguments[0], this.chart);
  this.chart.ctx.beginPath();
  this.chart.ctx.moveTo(eventPosition.x, 0);
  this.chart.ctx.strokeStyle = "#ff0000";
  this.chart.ctx.lineTo(eventPosition.x, this.chart.height);
  this.chart.ctx.stroke();

  return ret;
};

<canvas id="myChart" height=200/>

0 个答案:

没有答案