87,993
社区成员
发帖
与我相关
我的任务
分享
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
body {
text-align: center;
}
#c2 {
background: #f0f0f0;
}
</style>
</head>
<body>
<canvas id="c2"></canvas>
<h1>Canvas绘制统计图</h1>
<script>
var c2 = document.getElementById("c2");
var w = 800; //画布的宽
var h = 600; //画布的高
c2.width = w;
c2.height = h;
var ctx = c2.getContext('2d');
//绘制边框轮廓
ctx.strokeRect(50, 50, w - 100, h - 100);
var list = [
{label: 1, value: 300},
{label: 2, value: 400},
{label: 3, value: 200},
{label: 4, value: 490},
{label: 5, value: 350},
{label: 6, value: 450}
];
//每次更新的高度
var count = list.length;
//每个柱子的宽度
var colWidth = (w - 100) / (2 * count + 1);
//遍历list数据,绘制每个柱子
for (var i = 0; i < list.length; i++) {
(function (i) {
var rh1 = 0;
var data = list[i]; //每个数据
var rw = colWidth; //矩形的宽
var rh = data.value; //矩形的高
var x = (2 * i + 1) * colWidth + 50;
var y = h - rh - 50;
// ctx.strokeRect(x, y, rw, rh);
// ctx.fillStyle = 'red';
// ctx.fillRect(x, y, rw, rh);
var timer = setInterval(function () {
//清画布
//ctx.clearRect(0, 0, 800, 600);
rh1 += 5;
ctx.strokeRect(x, y, rw, rh1);
ctx.fillStyle = 'red';
ctx.fillRect(x, y, rw, rh1);
if (rh1 == rh) {
clearInterval(timer);
}
}, 50);
})(i);
}
</script>
</body>
</html>