效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/118d7ae7789bee101cfd2f5c60d84978.png)
<canvas></canvas>
var arr = [
{ id: 1001, price: 231 },
{ id: 1002, price: 451 },
{ id: 1003, price: 100 },
{ id: 1004, price: 142 },
{ id: 1005, price: 124 },
{ id: 1003, price: 100 },
{ id: 1004, price: 142 },
{ id: 1005, price: 124 },
];
var gap = 20;
var max;
var canvas = document.querySelector("canvas");
var cxt
init();
function init() {
canvas.width = 400;
canvas.height = 400;
cxt = canvas.getContext("2d");
animation()
}
function animation(){
arr.forEach(item=>{
item.color=getColor()
})
max=arr.reduce((value,item)=>{
console.log(value,item);
if(value>item.price) return value;
return item.price;
},arr[0].price);
var scaleHeight=400/5*4/max;
var width = (400 - (gap * (arr.length + 1))) / arr.length;
createChart(width,scaleHeight);
}
function createChart(w,hs){
cxt.clearRect(0,0,400,400);
cxt.fillStyle="rgba(0,0,0,0.3)";
cxt.fillRect(0,0,400,400);
var x=0;
for (let i = 0; i < arr.length; i++) {
x+=gap;
cxt.fillStyle=arr[i].color;
var h=hs*arr[i].price;
cxt.fillRect(x, 400 - h, w, h);
x+=w;
}
}
function getColor(){
var color="rgba(";
for (let i = 0; i < 3; i++) {
color +=Math.floor(Math.random()*256)+",";
}
color =color.slice(0,-1)+")";
return color;
}