简体   繁体   中英

Howto draw horizontalBar with dynamic thickness (automatic rescale on browser window height resize) in Chart.js 2.9.3?

I use latest Chart.js 2.9.3 .

I'm trying to draw a horizontal bar with thickness that depends on browser window size: from 50 when browser window is fullscreen, to 20 when browser window is resized to very small height.

I've tried the following code - but bar is always 50 ( https://jsfiddle.net/zg6c54rt/1/ ):

 var ctx = document.getElementById('chart').getContext('2d'); var chart = new Chart(ctx, { type: 'horizontalBar', data: { labels: ['1', '2', '3', '4'], datasets: [{ barThickness: 'flex', maxBarThickness: 50, data: [100, 90, 85, 95] }] }, options: { scales: { xAxes: [{ ticks: { min: 0 } }] } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script> <div class="text-center"> <canvas id="chart"></canvas> </div>

Changing barThickness: 'flex', to barThickness: 20, makes bar always 20 .

Not defining barThickness results in bar is always 50 (same as barThickness: 'flex' ).

Howto draw horizontalBar with dynamic thickness?

Thank you in advance.

Instead of using barThickness , you could define categoryPercentage together with barPercentage

datasets: [{
  categoryPercentage: 1, 
  barPercentage: 0.5,
  data: [100, 90, 85, 95]
}]

categoryPercentage : Percent (0-1) of the available width each category should be within the sample width.

barPercentage : Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other.

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