【问题标题】:How to fill a graph by a color till a vertical line using chart.js如何使用chart.js用颜色填充图表直到垂直线
【发布时间】:2017-11-10 19:21:38
【问题描述】:

enter image description here我正在尝试使用 chart.js 在折线图中显示垂直线。我使用fiddle 作为参考。

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(undefined, index), yaxis.top);
      ctx.strokeStyle = '#ff0000';
      ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.bottom);
      ctx.stroke();
      ctx.restore();
    }
  }
});

var config = {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First dataset",
      data: [65, 0, 80, 81, 56, 85, 40],
      fill: false
    }],
    lineAtIndex: 2
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);

在此,我想将值动态传递给 At Index 行,并且我想将图形灰显直到该垂直线。例如,如果线在位置 3,我想在该位置应用一些颜色。

【问题讨论】:

  • 欢迎来到 Stack Overflow!我编辑了你的问题的标题,以便更容易理解。我已经包含了小提琴中的代码示例。请尝试更具体地说明您已经尝试过的内容。编辑示例以仅包含代码的相关部分可能很有用。添加所需输出的图像也很有用。
  • 嗨 IvanH,感谢您编辑我的问题。我已经上传了图片。我能够显示两个折线图,但我不确定如何使用滑块滚动该垂直线。我虽然将滑块值传递给 lineAtIndex 以便垂直线将出现在该特定点。请帮我解决这个问题

标签: javascript chart.js chart.js2


【解决方案1】:

您可以将数据集拆分为 2,只需将具有区域的部分的填充属性设置为 true,将没有区域的部分设置为 false。您的新数据集将如下所示:

datasets: [{
      label: "My First dataset",
      data: [65, 0, 80],
      fill: true
    }, {
      label: "My First dataset",
      data: [null, null, 80, 81, 56, 85, 40],
      fill: false
    }
]

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 2017-03-10
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2015-04-04
    • 2012-06-06
    相关资源
    最近更新 更多