Chart js - 渲染后获取条形宽度

Gre*_* Od 5 javascript charts chart.js

我需要以像素为单位获取条形宽度,并将其用于pointRadius: {{barwidth}}重叠折线图的图表 js 设置。我的图表也设置为响应式,因此如果要调整窗口大小,我需要更新此值。

我难住了。并且真的可以使用一些帮助。

查看每个条形上的线条

那是一个带有pointStyle: 'line'集合的折线图,所以我可以有这个效果。现在我需要将该线的宽度设置为条形pointRadius: {{barwidth}}

ɢʀᴜ*_*ᴜɴᴛ 8

通常您可以使用getDatasetMeta()图表的方法来获取条形宽度。

但是,如果您要动态更改/更新折线图的点半径(在窗口调整大小时),则必须使用图表插件,例如:

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;
      }
   }
});
Run Code Online (Sandbox Code Playgroud)

* 在脚本的开头添加这个

????

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;
      }
   }
});
Run Code Online (Sandbox Code Playgroud)
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
            }
         }]
      }
   }
});
Run Code Online (Sandbox Code Playgroud)