Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting chart js bar chart to fill window

Tags:

chart.js

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?

like image 557
RGriffiths Avatar asked Jan 07 '23 03:01

RGriffiths


2 Answers

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

like image 158
MUlferts Avatar answered Mar 24 '23 22:03

MUlferts


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;
  }
}
like image 33
ego Avatar answered Mar 24 '23 20:03

ego