js实现柱状图
使用原生JavaScript实现柱状图
在HTML中创建画布元素
<canvas id="barChart" width="400" height="300"></canvas>
获取画布上下文并设置基础样式
const canvas = document.getElementById('barChart');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#3498db';
ctx.strokeStyle = '#2980b9';
ctx.lineWidth = 2;
定义数据和图表参数
const data = [45, 72, 38, 64, 89];
const barWidth = 50;
const gap = 30;
const startX = 60;
const baseY = canvas.height - 50;
绘制柱状图
data.forEach((value, index) => {
const x = startX + index * (barWidth + gap);
const barHeight = (value / 100) * (baseY - 50);
ctx.fillRect(x, baseY - barHeight, barWidth, barHeight);
ctx.strokeRect(x, baseY - barHeight, barWidth, barHeight);
ctx.fillStyle = '#2c3e50';
ctx.font = '14px Arial';
ctx.fillText(value, x + barWidth/2 - 10, baseY - barHeight - 10);
ctx.fillStyle = '#3498db';
});
添加坐标轴和标签

ctx.beginPath();
ctx.moveTo(40, 30);
ctx.lineTo(40, baseY);
ctx.lineTo(canvas.width - 20, baseY);
ctx.strokeStyle = '#7f8c8d';
ctx.stroke();
ctx.fillStyle = '#2c3e50';
ctx.fillText('数值', 20, 20);
ctx.fillText('类别', canvas.width - 40, baseY + 30);
使用Chart.js库实现柱状图
引入Chart.js库
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
准备HTML容器
<div style="width: 80%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
创建柱状图实例

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['一月', '二月', '三月', '四月', '五月'],
datasets: [{
label: '月度销售额',
data: [65, 59, 80, 81, 56],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
响应式柱状图实现
添加窗口大小变化监听
window.addEventListener('resize', function() {
myChart.resize();
});
设置图表容器响应式样式
.chart-container {
position: relative;
width: 100%;
min-height: 300px;
}
动态数据更新
添加数据更新方法
function updateChart(newData) {
myChart.data.datasets[0].data = newData;
myChart.update();
}
示例数据更新调用
setTimeout(() => {
updateChart([30, 45, 60, 75, 90]);
}, 2000);






