[Chartjs]-Canvas static height Chartjs

31👍

options: {
  responsive: true, 
  maintainAspectRatio: false
}

It works perfectly with these options.

12👍

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.

6👍

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.

4👍

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
}

Leave a comment