简体   繁体   中英

Chart js - Get bar width after render

I need to get the bar width in pixels and use it in my chart js settings for the pointRadius: {{barwidth}} of the overlapping line graph. My chart is also set to responsive so i'd need to update this value if the window was to be resized.

I am stumped. And could really use some help.

See the line on each bar

that is a line chart with the pointStyle: 'line' set so i can have this effect. Now i need to set the width of that line to the bar with pointRadius: {{barwidth}}

Usually you can use getDatasetMeta() method of the chart to get bar width.

However, if you were to change/update the point-radius of the line graph dynamically (on window resize), you would have to use a chart plugin, as such :

Chart.plugins.register({
   updated: false,
   beforeDraw: function(chart) {
      var barWidth = chart.getDatasetMeta(1).data[0]._model.width;
      var line = chart.data.datasets[0];
      line.pointRadius = barWidth / 2;
      line.pointHoverRadius = barWidth / 2;
      if (!this.updated) {
         chart.update();
         this.updated = true;
      }
   }
});

* add this at the beginning of your script

ᴅᴇᴍᴏ ⧩

 Chart.plugins.register({ updated: false, beforeDraw: function(chart) { var barWidth = chart.getDatasetMeta(1 /* dataset-index of bar graph */).data[0]._model.width; var line = chart.data.datasets[0 /* dataset-index of line graph */]; line.pointRadius = barWidth / 2; line.pointHoverRadius = barWidth / 2; // update chart at first render with newly added values if (!this.updated) { chart.update(); this.updated = true; } } }); var chart = new Chart(ctx, { type: 'bar', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'], datasets: [{ type: 'line', label: 'LINE', data: [3, 1, 4, 2, 5], backgroundColor: 'rgba(0, 119, 290, 0.5)', borderColor: 'transparent', pointBorderColor: '#07C', fill: false, pointStyle: 'line' }, { label: 'BAR', data: [3, 1, 4, 2, 5], backgroundColor: 'rgba(4, 142, 128, 0.5)' }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script> <canvas id="ctx"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM