Canvas写柱状图

效果图

在这里插入图片描述

<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");
            // setInterval(animation, 16);
            animation()
        }
        function animation(){
            arr.forEach(item=>{
                // var random=Math.floor(Math.random()*10);
                // item.price+=random;
                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;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值