Beezle-Bug
Beezle-Bug

Reputation: 167

How to resize chart.js graph dynamically for responsive sites?

Hej, I know this has been answered in one way or the other many times, but I really can't get it work in my context with flex-boxes.

I have fixed elements, such as headers and footers on my page, and a chart that shall take up all the remaining space in between. While it appears to be working on first glance, you can see that the text and numbers are blurred and not properly scaled when the window is resized.

How can I fix this, or have chart.js redraw the canvas upon resize?

Check out my fiddle https://jsfiddle.net/fg9pd1b3/

<body>
  <div class="container">
    <div class="fixed">
      header
    </div>
    <div id="chartcontainer">
      <canvas id="chartJSContainer"></canvas>
    </div>
    <div class="fixed">
      footer
    </div>
  </div>
</body>

CSS:

html,
body {
  height: 100vh;
  min-height: 100vh;
  max-height: 100vh;
  margin: 0;
  padding: 0;
}

.container {
  width: 80%;
  height: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  flex-basis: 100%;
  flex-grow: 1;
  background: #CCC;
}

.p {
  text-align: center;
  font-size: 14px;
  padding-top: 140px;
}

.fixed {
  background: black;
  height: 100px;
  min-height: 100px;
  color: white;
  text-align: center;
}

#chartcontainer {
  position: relative;
  min-height: 200px;
  display: flex;
  flex-grow: 1;

}

canvas {
  width: 100% !important;
  height: 100% !important;
}

JS:

Chart.defaults.global.responsive = true;
var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

Upvotes: 0

Views: 5335

Answers (1)

Thafzil Ahamed
Thafzil Ahamed

Reputation: 19

You have given fixed min-height to the canvas div which restricts the chart to further change it's dimensions. So, the following code has auto height and width automates to 100% which gives flexible chart.

#chartcontainer {
  position:relative;
  min-height:auto;
  width:100%;
  display: flex;
  flex-grow:1;
}

Upvotes: 2

Related Questions