4

I have a chart js bar chart that draws within the canvas:

<canvas id="chart" width="800" height="400"></canvas>

However I would like the chart to fit the size of the current window. I have tried:

<canvas id="chart" width="100%" height="400"></canvas>

but it does not like it. I could get the window width using window.innerWidth but is there any reason why the 100% does not work?

RGriffiths
  • 5,722
  • 18
  • 72
  • 120

2 Answers2

8

Please see the post: Chart.js canvas resize . There are actually two answers that are really good solutions here. You can use the chart options like below:

// Boolean - whether or not the chart should be responsive and resize when the browser does.

responsive: true,

// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container

maintainAspectRatio: false,

or you can set the canvas width and height using client side code:

var ctx = document.getElementById("canvas").getContext("2d");
ctx.canvas.width = 300;
ctx.canvas.height = 300;
var myDoughnut = new Chart(ctx).Doughnut(doughnutData);

This post very effectively answers your question about why % values dont work: Canvas is stretched when using CSS but normal with "width" / "height" properties

Community
  • 1
  • 1
MUlferts
  • 1,310
  • 2
  • 16
  • 30
  • Thanks. Purely by accident I have found that by putting responsive:true in the options does the job perfectly. – RGriffiths May 04 '16 at 13:13
  • Great, no problem. I had trouble with that same issue when starting to work with this library as well. Maybe you can mark this as an answer so others can use it as reference. – MUlferts May 04 '16 at 13:16
2

After setting responsive and ratio options (check out related chartjs doc), use following css to fill 100% of the parent:

html

<div class="panel">
  <div class="chart-container">
    <canvas id="chart"></canvas>
  </div>
</div>

scss:

.panel {
  display: flex;

  .chart-container {
    position: relative;
    flex-grow: 1;
    min-height: 0;
  }
}
Be Kind
  • 4,712
  • 1
  • 38
  • 45