Reputation: 3658
I am using chart.js 2.3.0 to draw graph. I want to make the height of the graph static(fixed e.g. 200px) but also want to set the width to 100%. One solution I have seen is to do:
responsive: false
in the graph options. But after doing this, width also reduces. Is there any best way to do it?
static height and 100% width.
Upvotes: 16
Views: 30107
Reputation: 3658
options: {
responsive: true,
maintainAspectRatio: false
}
It works perfectly with these options.
Upvotes: 32
Reputation: 1071
This question has an accepted answer, but it was only part of the answer for me. What isn't clear from the documentation, at least to me, is that you must set the height of the parent element of the canvas, otherwise with maintainAspectRatio: false the height will be zero.
This is what worked for me using Bootstrap 4 cards (inline style for illustration):
<div class="card">
<div class="card-body" style="height: 400px;">
<canvas id="myChart"></canvas>
</div>
</div>
Then adding these this to the options:
options: {
maintainAspectRatio: false
}
By default responsive is set to true.
This also allows the easy use of responsive breakpoints and media queries to resize the chart.
Upvotes: 6
Reputation: 241
To make it work, you also need to wrap your chart in a dedicated element in addition of using these options:
options: {
responsive: true,
maintainAspectRatio: false
}
Example:
<div>
<canvas id="xxx"></canvas>
</div>
See official documentation:
Detecting when the canvas size changes can not be done directly from the CANVAS element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only.
Upvotes: 13
Reputation: 1312
If you want to break the aspect ratio you can use the maintainAspectRatio
option from the docs. Your height and width should be taken from the canvas set values then or use css to set styles for the canvas element.
options: {
responsive: false,
maintainAspectRatio: false
}
Upvotes: 4