I would like to increase the height of the horizontal bar chart, based on the amount of categories in my dataset.
The problem is, that chartjs renders the bar chart as if it is rendering it in the original height of the canvas container, but if I run my code twice it does resize to the correct size.
To do this, I wrote this function:
function requiredCanvasHeightBasedOnBars(data, barThickness, truncate) {
// only works for horizontal barcharts
var totalNrOfBars = data.length;
var amountOfBarsToRender = (totalNrOfBars < truncate ? totalNrOfBars : truncate);
var requiredHeight = barThickness * amountOfBarsToRender * 2 + 20; // times 2 for ballpark extra spacing between bars, plus 20 for xAxis.
return requiredHeight;
};
I wrote this code to update the height of the chart when the user clicks on a ' expand ' button.
if (data.length > barTruncateAmount) {
renderExpandButton(container, function () {
var canvasHeight = requiredCanvasHeightBasedOnBars(data, barThickness, 999);
container.querySelector('.def-canvasContainer').setAttribute('style', 'height: ' + canvasHeight + 'px;');
canvas.height = canvasHeight;
canvas.style.height = canvasHeight + 'px';
chart.options.scales.y.max = 999;
chart.update();
chart.resize();
});
}
code of expand button
function renderExpandButton(container, updateChartCallback) {
// create button
var expandButton = document.createElement('button');
var buttonText = document.createTextNode('Expand');
expandButton.setAttribute('class', 'js-expandButton');
expandButton.setAttribute('type', 'button');
expandButton.appendChild(buttonText);
// 2. listener to the html button
expandButton.addEventListener('click', function (event) {
updateChartCallback();
})
container.appendChild(expandButton);
}
The options in my chart are:
responsive: true,
maintainAspectRatio: false,
When a user taps the button, the container height changes, yet the bar chart re-renders in the same smaller area from before. When I click the button again, it does fill the whole space!
I've been struggling to find out for hours now. Anyone know why it doesn't fill the whole space after the first click?