Skip to content
","url":"https://ez4code.com/snippets/chartjs-responsive-chart","keywords":"chart, responsive","author":{"@type":"Person","name":"EZ4Code Team"},"publisher":{"@type":"Organization","name":"EZ4Code","logo":{"@type":"ImageObject","url":"https://ez4code.com/logo.png"}},"datePublished":"2024-01-01","dateModified":"2026-08-01","image":"https://ez4code.com/og-image.png"}
Chart.js

Responsive Chart

Chart that fills its container with maintainAspectRatio disabled.

By EZ4Code Team
chartresponsive

Code

<!-- Container controls the size; canvas fills it -->
<div style="height: 320px; width: 100%;">
  <canvas id="myChart"></canvas>
</div>

<script>
function createResponsiveChart(canvasId) {
  const ctx = document.getElementById(canvasId).getContext('2d');
  return new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['A', 'B', 'C', 'D'],
      datasets: [{ data: [10, 20, 15, 25] }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      aspectRatio: 3,
      resizeDelay: 0,
      onResize(chart, size) {
        console.log('Resized:', size.width, 'x', size.height);
      },
      plugins: { legend: { display: false } }
    }
  });
}

const chart = createResponsiveChart('myChart');
window.addEventListener('resize', () => chart.resize());
</script>

Explanation

For full control over height, set maintainAspectRatio:false and wrap the canvas in a sized div; Chart.js will then fill the container and re-render on resize. The onResize callback fires with the new size, and resizeDelay debounces rapid layout changes. Call chart.resize() manually when the container changes outside of window resize.

More Chart.js Snippets