Responsive Chart
Chart that fills its container with maintainAspectRatio disabled.
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
Bar Chart
Vertical bar chart with custom colors and rounded corners.
Line Chart
Smooth line chart with fill, tension, and hover styling.
Pie Chart
Pie chart with per-slice colors and legend positioning.
Doughnut Chart
Doughnut chart with cutout control and centered title.
Radar Chart
Multi-series radar chart for comparing entities across dimensions.
Options Configuration
Title, legend, axis formatting, animations, and live updates.