[Chartjs]-Chart.JS full-width, responsive doughnut chart with Bootstrap

14👍

If you want to make it responsive and preserve aspect ratio, 2 things to consider:

1) In options:

{
   responsive: true,
   maintainAspectRatio: true, 
}

2) Define the aspect ratio by setting width and height attributes to the canvas. In your case they’re probably equal:

<canvas id="doughnut" 
    width="100"
    height="100"
    chart-data="data" 
    chart-labels="labels" 
    chart-options="mainDonut" 
    class="chart chart-doughnut">
</canvas>

1👍

It seems like the width of the chart is limited to whatever the height
of the div is, which for me is magically being set at about 300px by
ChartJS for some reason.

That’s the default width of the canvas element (http://www.w3.org/TR/html5/scripting-1.html#the-canvas-element).

This means that your responsive option is not actually doing what it’s supposed to. The most likely reason is that the the wrapping element does not have a (measurable) size when the chart is being initialized. For Angular, the most common reason is the wrapping (parent) elements not being in a fully rendered state when the chart is being initialized (eg. it has an ng-show or it’s a hidden tab, etc.).

CSS on the parent element could also be a problem – e.g. the parent elements don’t have a size (but looking at your markup this seems a bit unlikely)


Note – even though you don’t do a chart resize on window resize, Chart.js automatically does it for all charts that are configured as responsive.

1👍

function initChart() {
    var canvas = document.getElementById('chart-canvas');
    canvas.width = parent.offsetWidth;
    canvas.height = parent.offsetWidth; ... 
}

+css parent block {
   width: 100%;
   min-height: 300px;
}

Hope this will helps you.

Leave a comment