
Chart.js is a popular JavaScript library used to create beautiful, interactive charts in web applications. With its simplicity and flexibility, developers can quickly create a variety of chart types, such as bar, line, pie, and more, using just a few lines of code.
To use Chart.js, simply include the library in your project:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
Then, create a canvas element in your HTML where the chart will be rendered:
<canvas id="myChart" width="400" height="400"></canvas>
In your JavaScript, initialize the chart by specifying the chart type and data:
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line', // You can change this to 'bar', 'pie', etc.
data: {
labels: ['January', 'February', 'March', 'April'],
datasets: [{
label: 'Sales',
data: [12, 19, 3, 5],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
}
});
You can easily customize the appearance of your charts by adjusting settings like backgroundColor, borderColor, pointRadius, or tension to smooth or sharpen lines. Options can also disable certain features like tooltips or legends for a cleaner look.
options: {
responsive: true,
plugins: {
legend: { display: false },
tooltip: { enabled: false }
}
}
Chart.js is a powerful tool for visualizing data in a clean and customizable way. Whether you're building dashboards or simple reports, its wide range of chart types and easy integration make it a go-to choice for developers.