Chart.js,虚线,全宽图表

时间:2015-10-03 08:03:11

标签: javascript charts chart.js

是否可以在Chart.js折线图上创建虚线?并使图表全宽?见附件样机。

enter image description here

这是我目前的代码(只是简单示例):

    var ctx = document.getElementById("main-line-chart").getContext("2d");
    var line = ctx.setLineDash([5, 15]);

    var gradient = ctx.createLinearGradient(0, 0, 0, 300);
    gradient.addColorStop(0, 'rgba(40,175,250,.25)');
    gradient.addColorStop(1, 'rgba(40,175,250,0)');

    var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "My First dataset",
                pointDot : false,
                fillColor: gradient,
                strokeColor: "#28AFFA",
                pointColor: "#19283F",
                pointStrokeColor: "#28AFFA",
                pointHighlightFill: "#19283F",
                pointHighlightStroke: "#28AFFA",
                data: [65, 59, 80, 81, 56, null, null]
            },
            {
                label: "My Second dataset",
                fillColor: "rgba(0,0,0,0)",
                strokeColor: "rgba(255,255,255,.39)",
                pointColor: "#19283F",
                pointStrokeColor: "rgba(255,255,255,.39)",
                pointHighlightFill: "#19283F",
                pointHighlightStroke: "#28AFFA",
                data: [null, null, null, null, 56, 27, 90]
            }
        ]
    };

    var options = {};

    var myLineChart = new Chart(ctx).Line(data, options);
    console.log(myLineChart);

1 个答案:

答案 0 :(得分:0)

Chart.js 自从发布这个问题以来已经发展,但即使使用当前版本 2.9.4,该解决方案看起来与最初发布的代码几乎相同。

主要变化如下:

  • 我们现在应该使用 new Chart(ctx).Line(...) 而不是使用 type: 'line',如图here
  • 相当多的 dataset properties 有不同的名字。
  • 使用选项 borderDash 绘制第二个数据集的虚线。

请查看您修改后的代码,看看它是如何工作的。

var ctx = document.getElementById("main-line-chart").getContext("2d");
var gradient = ctx.createLinearGradient(0, 0, 0, 300);
gradient.addColorStop(0, 'rgba(40,175,250,.25)');
gradient.addColorStop(1, 'rgba(40,175,250,0)');

var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
      label: "My First dataset",
      backgroundColor: gradient,
      borderColor: "#28AFFA",
      pointColor: "#19283F",
      pointHighlightColor: "#28AFFA",
      data: [65, 59, 80, 81, 56, null, null]
    },
    {
      label: "My Second dataset",
      fill: false,
      borderColor: "rgba(100, 100, 100,.39)",
      pointColor: "#19283F",
      pointHighlightColor: "#28AFFA",
      data: [null, null, null, null, 56, 27, 90],
      borderDash: [10, 5]
    }
  ]
};

var options = {};
var myLineChart = new Chart(ctx, {
  type: "line",
  data: data,
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="main-line-chart" height="100"></canvas>