柱状图
<body>
<style>
#box {
border: 1px solid black;
}
</style>
<canvas id="box" width="600" height="600"></canvas>
<script>
var canvas = document.querySelector("#box")
var pen = canvas.getContext("2d")
// pen.rect(200,200,100,300)
// // pen.stroke()//画出线条,对于封闭图形,可以不用这个语句,用fill填充
// pen.fillStyle="red"
// pen.fill()//默认颜色黑色
//假数据
arr = [1990, 7504, 4807, 3024, 9675, 1400, 2699, 7463]
var x = 40
function drow() {
pen.beginPath()
pen.moveTo(20, 500)
pen.lineTo(580, 500)
pen.stroke()
//画柱状图
for (let i = 0; i < arr.length; i++) {
var y = arr[i] / 20
pen.beginPath(x + (i * 80), 500 - y)
pen.rect(x + (i * 80), 500 - y, 50, y)
var r = parseInt(Math.random() * 255)
var g = parseInt(Math.random() * 255)
var b = parseInt(Math.random() * 255)
//给柱状图加随机颜色
pen.fillStyle = `rgb(${r},${g},${b})`
pen.fill()
}
}
//添加计时器,将柱状图向左移动
setInterval(function () {
canvas.width = 600
x -= 20
drow()
}, 300)
//添加计时器,定时向数组中添加10000-1000的随加数
setInterval(function () {
var add = Math.random() * ((10000 - 1000) + 1000)
arr.push(add)
}, 1000)
</script>
</body>