如何在chart.js中制作矩形

时间:2017-11-04 07:10:47

标签: javascript jquery charts chart.js bar-chart

我正在尝试将矩形设置为chart.js中的上下范围/级别,如图像

enter image description here

虽然我可以通过在此示例中绘制两行来实现它

var ctx = document.querySelector("#myChart").getContext('2d');
Chart.pluginService.register({
    afterDraw: function(chart) {
        if (typeof chart.config.options.lineAt != 'undefined') {
        	var lineAt = chart.config.options.lineAt;
            var ctxPlugin = chart.chart.ctx;
            
            var xAxe = chart.scales[chart.config.options.scales.xAxes[0].id];
            
            ctxPlugin.strokeStyle = "green";
        	ctxPlugin.beginPath();
            lineAt = 102;
            ctxPlugin.moveTo(xAxe.left, lineAt);
            ctxPlugin.lineTo(xAxe.right, lineAt);
            ctxPlugin.moveTo(xAxe.left, lineAt-33);
            ctxPlugin.lineTo(xAxe.right, lineAt-33);
            ctxPlugin.stroke();
        }
    }
});
var myChart = new Chart(ctx, {
          type: 'bar',
          data: {
              labels: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Nov","Dec"],
              datasets: [{
                  label: 'Findings',
                  data: [0,45],
                  backgroundColor: 'rgba(54, 162, 235, 0.2)',
                  borderColor: 'rgba(54, 162, 235, 1)',
                  borderWidth: 1
              }]
          },
          options: {
          	lineAt: 15,
            scales: {
                yAxes: [{
                  display: true,
                  ticks: {
                      beginAtZero: true,
                      steps: 20,
                      stepValue: 20,
                      max: 60,
                      min: 0
                  }
              }]
            }
          }
      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>

请在此处分享您的建议:http://jsfiddle.net/nikleshraut/ad2fsefe/

1 个答案:

答案 0 :(得分:1)

已经存在一个名为chartjs-plugin-annotation的Chart.js插件,您可以通过该插件轻松实现这一目标。

使用该插件,您需要创建一个框注释(矩形),如下所示:

options: { //your chart options
   annotation: {
      annotations: [{
         type: 'box',
         drawTime: 'beforeDatasetsDraw',
         yScaleID: 'y-axis-0',
         yMin: 40,
         yMax: 50,
         backgroundColor: 'rgba(0, 255, 0, 0.1)'
      }]
   }
}

注意:这是绘制该矩形所需的最小选项,  你可以找到更多选项here

这是working fiddle