How to use the CSS Styling In JavaScript
Apply styles to the canvas element using CSS to control its size.
Syntax:
canvas {
width: 400px;
height: 200px;
}
Example: The below example explains the use of CSS styling to set the size of the canvas.
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 > < style > body { display: flex; flex-direction: column; align-items: center; justify-content: center; } /* CSS Styling for Canvas */ #chartContainer { text-align: center; } #cssStyledChart { width: 400px; height: 200px; } </ style > < title > CSS Styling - Chart.js </ title > </ head > < body > < div id = "chartContainer" > < h1 >w3wiki</ h1 > <!-- Canvas with CSS Styling --> < canvas id = "cssStyledChart" ></ canvas > < p > Example of "CSS Styling" for Chart.js </ p > </ div > < script > // Chart Data let data = { labels: ['January', 'February', 'March', 'April', 'May'], datasets: [{ label: 'Monthly Sales', data: [12, 19, 3, 5, 2], backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }; // Chart Configuration let config = { type: 'bar', data: data, options: { responsive: false, maintainAspectRatio: false, } }; // Create Chart let ctx = document. getElementById('cssStyledChart'). getContext('2d'); let cssStyledChart = 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>