How to make rectangle in chart.js

我的未来我决定 提交于 2020-03-05 05:23:06

问题


I am trying to put rectangle to make a upper-lower range/level in chart.js, like in image

Although I am able to make it by drawing two line in this example

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>

Please share your suggestion here : http://jsfiddle.net/nikleshraut/ad2fsefe/


回答1:


There is already a Chart.js plugin exists called chartjs-plugin-annotation, by which you can achieve that much easily.

Using that plugin, you'll need to create a box annotation (rectangle), as such :

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)'
      }]
   }
}

note: this is the minimum options required to draw that rectangle, and you can find more options here.

Here is a working fiddle.



来源:https://stackoverflow.com/questions/47108389/how-to-make-rectangle-in-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!