By using the style attribute
We can set the height and the width as CSS properties for the container containing the canvas of our chart inside the style attribute.
Syntax:
<div style=" height:40vh; width:80vw">
<canvas id="myChart"></canvas>
</div>
Example: The below code will explain the use of the style attribute to set the height and the width of the chart.
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 style="height:40vh; width:80vw"> < canvas id = "myChart" > </ canvas > </ div > </ div > < script > var 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: { 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>