写一个x轴从一月到十二月,y轴从2000,4000,6000,8000的html柱状图
时间: 2024-10-09 22:05:45 浏览: 50
echarts漂亮的柱状图按月统计
要在HTML中创建一个简单的柱状图,我们可以利用`<canvas>`元素结合JavaScript和一些基本数据。下面是一个简单的例子,展示了一个x轴表示月份,y轴代表数值(2000、4000、6000、8000)的柱状图:
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>柱状图示例</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="barChart" width="400" height="300"></canvas>
<script>
// 数据
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const values = [2000, 4000, 6000, 8000, 2000, 4000, 6000, 8000, 2000, 4000, 6000, 8000];
// 获取canvas元素并初始化绘图上下文
const canvas = document.getElementById('barChart');
const ctx = canvas.getContext('2d');
// 绘制x轴和y轴刻度
function drawAxis() {
// x轴刻度
for (let i = 0; i <= months.length; i++) {
if (i > 0) {
ctx.fillText(months[i - 1], 50, i * 30 + 20);
}
}
// y轴刻度
for (let j = 0; j <= values.reduce((a, b) => Math.max(a, b)); j += 2000) {
ctx.beginPath();
ctx.moveTo(5, canvas.height - j);
ctx.lineTo(canvas.width, canvas.height - j);
ctx.stroke();
ctx.fillText(`${j}`, 40, canvas.height - j - 10);
}
}
// 绘制柱状图
function drawBar(monthIndex, value) {
const barWidth = canvas.width / months.length;
ctx.fillStyle = 'blue';
ctx.fillRect(monthIndex * barWidth + 10, canvas.height - value, barWidth - 20, value);
}
// 渲染图表
drawAxis();
months.forEach((month, index) => drawBar(index, values[index]));
// 添加事件监听,以便交互(例如点击显示数值)
canvas.addEventListener('click', function(e) {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const monthIndex = Math.floor(x / canvas.width * months.length);
if (monthIndex >= 0 && monthIndex < months.length) {
console.log(`Clicked on ${months[monthIndex]} with value ${values[monthIndex]}`);
}
});
</script>
</body>
</html>
```
阅读全文