Why Chart.js?
Chart.js is the most popular JavaScript charting library for good reason:
- ✓Load with one
<script>tag — no npm or build tools - ✓Beautiful charts out of the box with animations
- ✓Responsive by default — resizes with the window
- ✓Highly customizable — colors, fonts, tooltips, legends
- ✓Free and open source
Setup — One Script Tag
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>
That is all you need to start drawing charts.
Creating a Bar Chart
const ctx = document.getElementById('bar-chart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
datasets: [{
label: 'Monthly Sales',
data: [120, 190, 150, 210, 180, 240],
backgroundColor: 'rgba(184,134,11,0.8)',
borderRadius: 6,
}]
},
options: { responsive: true }
});
Line Chart with Gradient Fill
The gradient fill under a line chart makes data trends visually clear:
const gradient = ctx.createLinearGradient(0, 0, 0, 300);
gradient.addColorStop(0, 'rgba(184,134,11,0.3)');
gradient.addColorStop(1, 'rgba(184,134,11,0.0)');
datasets: [{
data: revenueData,
fill: true,
backgroundColor: gradient,
tension: 0.4, // smooth curves
}]
Doughnut Chart with Custom Center Label
Chart.js plugins let you draw custom content on the canvas:
const centerTextPlugin = {
id: 'centerText',
afterDraw(chart) {
const { ctx, chartArea: { top, bottom, left, right } } = chart;
const cx = (left + right) / 2;
const cy = (top + bottom) / 2;
const total = chart.data.datasets[0].data.reduce((a,b) => a+b, 0);
ctx.save();
ctx.textAlign = 'center';
ctx.font = 'bold 28px sans-serif';
ctx.fillStyle = '#B8860B';
ctx.fillText(total, cx, cy);
ctx.restore();
}
};
Live Data Update
function refreshCharts() {
barChart.data.datasets[0].data = generateNewData();
barChart.update(); // Re-renders with animation
}
document.getElementById('refresh-btn').addEventListener('click', refreshCharts);
This is a preview. The full ebook includes the complete dark-themed dashboard layout, all 4 charts with full configuration, stats cards with total/average/high/low calculations, and a light theme override guide.
