Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic Height for Chart.js

I'm following the documentation correctly with Chart.js and my Bar Chart is appearing too big until I click inspect element, then the chart seems to resize and snap into the correct position.

Quick Screencast of Issue

There's no inline styles on my canvas element, the following styles come into play once I go to Inspect Element. I'm not sure where or how the chart is getting those inline styles.

canvas{
 width: 100% !important;
 max-width: 800px;
 height: auto !important;}
like image 693
ItsJoeTurner Avatar asked Oct 31 '22 09:10

ItsJoeTurner


1 Answers

Try

var barChart = new Chart(ctx, {
  type: 'bar',
  responsive: true,
  maintainAspectRatio: false,
  data: {
    ...
  },
  options: {
    animation: {
      onComplete: function (animation) {
        this.options.animation.onComplete = null; // disable after the first render
        animation.chartInstance.resize()
      }
    }
  }
});

as an alternative, why do you set the width to 100% but not the height? In your screen vid it's inside of another div anyways so I'd try playing w/ the height too. Finally, I'd refrain from using the global canvas CSS selector -- rather use canvas#barChart because otherwise it'll be applied to all canvases, not just the chartjs ones.

like image 110
Joe - Elasticsearch Handbook Avatar answered Nov 11 '22 17:11

Joe - Elasticsearch Handbook