效果图:
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#canvas {
background-color: antiquewhite;
border: 1px solid gold;
}
</style>
</head>
<body>
<canvas id="canvas" height="250px" width="450px"></canvas>
<script>
let cvs = document.getElementById("canvas");
let ctx = cvs.getContext("2d");
//准备好已知数据,实际开发中是通过请求网络数据获取
let values = [120, 200, 150, 240, 80, 150, 220];
let cvs_w = 450; //画布宽度
let cvs_h = 250; //画布高度
let bar_w = 50; //柱子宽度
//计算绘制柱状图时需要的4个数组:x,y,w,h
let xs = [];
let ys = [];
let ws = [];
let hs = [];
let fx = (cvs_w - bar_w * values.length) / (2 * values.length);
//对values进行遍历
values.forEach((item, i) => {
xs.push(i * 50 + fx * (2 * i + 1));
ys.push(cvs_h - item);
ws.push(bar_w);
hs.push(item);
});
//遍历values,绘制每一根柱子
for (let i = 0; i < values.length; i++) {
ctx.fillStyle = "blue";
ctx.fillRect(xs[i], ys[i], ws[i], hs[i]);
//输出文本
ctx.fillStyle = "#fff";
ctx.font = "20px 幼圆";
ctx.textAlign = "center";
ctx.fillText(values[i], xs[i] + 25, ys[i] + 20);
}
</script>
</body>
</html>