By setting height and width as attribuutes
We can set the height and the width by passing them as attributes directly to the canvas of our chart. We also have to set responsive to false within options for width to work correctly.
Syntax:
<canvas id="myChart" height="200" width="500"></canvas>
// In Options
options: {
responsive: false,
}
Example: The below example will show how you can set height nad width of the chart using the attributes.
HTML
<!DOCTYPE html> < html > < head > < title >Chart.js - Set Height and Width</ title > < script src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js" > </ script > </ head > < body > < div > < div > < canvas id = "myChart" height = "300" width = "600" > </ canvas > </ div > </ div > < script > const ctx = document. getElementById('myChart'). getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [{ label: 'My Dataset', data: [65, 71, 62, 81, 34, 55, 47], backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }, options: { responsive: false, scales: { y: { beginAtZero: true } } } }); </ script > </ body > </ html > |
Output:
How to Set Height and Width of a Chart in Chart.js ?
Chart.js is a popular JavaScript library that allows developers to create interactive and visually appealing charts for web applications. One of the key aspects of chart customization is controlling its dimensions. In this article, we’ll explore how to set the height and width of a Chart.js chart.
Chart.js CDN link
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
Contact Us