Me gustaría aumentar la altura del gráfico de barras horizontales, según la cantidad de categorías en mi conjunto de datos.
El problema es que chartjs representa el gráfico de barras como si lo estuviera representando en la altura original del contenedor del lienzo, pero si ejecuto mi código dos veces, cambia el tamaño al tamaño correcto.
Para hacer esto, escribí esta función:
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; };Escribí este código para actualizar la altura del gráfico cuando el usuario hace clic en el botón 'expandir'.
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(); }); }código del botón expandir
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); }Las opciones en mi gráfico son:
responsive: true, maintainAspectRatio: false,Cuando un usuario toca el botón, la altura del contenedor cambia, pero el gráfico de barras se vuelve a representar en la misma área más pequeña que antes. Cuando vuelvo a hacer clic en el botón, ¡llena todo el espacio!
He estado luchando para averiguarlo durante horas. ¿Alguien sabe por qué no llena todo el espacio después del primer clic?