Skip to content
Chart.js

Responsive Chart

Chart that fills its container with maintainAspectRatio disabled.

#chart#responsive

Code

chartjs
<!-- 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>