How to use Options In JavaScript
Configure the canvas size by specifying options within the JavaScript code when initializing the chart.
Syntax:
options: {
responsive: false,
maintainAspectRatio: false,
// Set your size options here
aspectRatio: 2,
// or
width: 400,
height: 200
}
Example: The below code will show how you can add the options to set the canvas size for every type of chart.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> < script src = "https://cdn.jsdelivr.net/npm/chart.js" > </ script > < title > JavaScript Options - Chart.js </ title > < style > body { display: flex; flex-direction: column; align-items: center; justify-content: center; margin: 0; } /* Center the canvas */ #chartContainer { text-align: center; } </ style > </ head > < body > < div id = "chartContainer" > < h1 >w3wiki</ h1 > <!-- Canvas for JavaScript Options --> < canvas id = "jsOptionsChart" width = "400" height = "200" > </ canvas > < p > Example of "Using JavaScript Options" </ p > </ div > < script > // Chart Data let data = { labels: ['January', 'February', 'March', 'April', 'May'], datasets: [{ label: 'Monthly Sales', data: [8, 21, 3, 15, 2], backgroundColor: 'rgba(75, 109, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }; // Chart Configuration with // JavaScript Options let config = { type: 'bar', data: data, options: { responsive: false, maintainAspectRatio: false, width: 400, height: 200 } }; // Create Chart let ctx = document. getElementById('jsOptionsChart'). getContext('2d'); let jsOptionsChart = new Chart(ctx, config); </ script > </ body > </ html > |
Output:
How to Set the Size of Canvas for Every Type of Chart ?
In this article, we will learn various approaches to setting the size of the canvas for different chart types using Chart.js. When you work with charting libraries like Chart.js, one common requirement is to customize the size of the canvas for different types of charts.
There are multiple ways to set the canvas size in Chart.js:
Table of Content
- Using Inline Configuration
- Using JavaScript Options
- Using the CSS Styling
Chart.js CDN Link
Include the below chart.js CDN in your HTML document.
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>