成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

怎么在html5中使用canvas實現(xiàn)柱狀圖

這篇文章給大家介紹怎么在html5中使用canvas實現(xiàn)柱狀圖,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

云霄網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián),云霄網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為云霄上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站制作要多少錢,請找那個售后服務(wù)好的云霄做網(wǎng)站的公司定做!

使用方式

首先我們看一下使用方式,參考了部分ECharts的使用方式,先傳入要顯示圖表的html標(biāo)簽,接著調(diào)用init,初始化的同時傳入數(shù)據(jù)。

var con=document.getElementById('container');
    var chart=new Bar(con);
    chart.init({
        title:'全年降雨量柱狀圖',
        xAxis:{// x軸
            data:['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
        },
        yAxis:{//y軸
            name:'水量',
            formatter:'{value} ml'
        },
        series:[//分組數(shù)據(jù)
            {
                name:'東部降水量',
                data:[62,20,17,45,100,56,19,38,50,120,56,130]
            },
            {
                name:'西部降水量',
                data:[52,10,17,25,60,39,19,48,70,30,56,8]
            },
            {
                name:'南部降水量',
                data:[12,10,17,25,27,39,50,38,100,30,56,90]
            },
            {
                color:'hsla(270,80%,60%,1)',
                name:'北部降水量',
                data:[12,30,17,25,7,39,49,38,60,30,56,10]
            }
        ]
    });

圖表基類,我們后面還要寫餅圖,折線圖,所以把公共的部分抽出來。注意canvas.style.width與canvas.width是不一樣的,前者會拉伸圖形,后者才是我們正常用的,不會拉伸圖形。在這里這樣寫先擴大再縮小是為了解決canvas繪制文字時模糊的問題。

class Chart{
        constructor(container){
            this.container=container;
            this.canvas=document.createElement('canvas');
            this.ctx=this.canvas.getContext('2d');
            this.W=1000*2;
            this.H=600*2;
            this.padding=120;
            this.paddingTop=50;
            this.title='';
            this.legend=[];
            this.series=[];
            //通過縮小一倍,解決字體模糊問題
            this.canvas.width=this.W;
            this.canvas.height=this.H;
            this.canvas.style.width = this.W/2 + 'px';
            this.canvas.style.height = this.H/2 + 'px';
        }
    }

柱狀圖初始化,調(diào)用es6中的Object.assign(this,opt),這個相當(dāng)于JQ中的extend方法,把屬性復(fù)制到當(dāng)前實例。同時還建了個tip屬性,這是個html標(biāo)簽,后面顯示數(shù)據(jù)信息用。接著繪制圖形,然后綁定鼠標(biāo)事件。

class Bar extends Chart{
    constructor(container){
        super(container);
        this.xAxis={};
        this.yAxis=[];
        this.animateArr=[];
    }
    init(opt){
        Object.assign(this,opt);
        if(!this.container)return;
        this.container.style.position='relative';
        this.tip=document.createElement('div');
        this.tip.style.cssText='display: none; position: absolute; opacity: 0.5; background: #000; color: #fff; border-radius: 5px; padding: 5px; font-size: 8px; z-index: 99;';
        this.container.appendChild(this.canvas);
        this.container.appendChild(this.tip);
        this.draw();
        this.bindEvent();
    }
    draw(){//繪制

    }
    showInfo(){//顯示信息

    }
    animate(){//執(zhí)行動畫

    }
    showData(){//顯示數(shù)據(jù)

    }

繪制XY軸

首先繪制標(biāo)題,接著XY軸,然后遍歷分組數(shù)據(jù)series,里面有復(fù)雜的計算,然后繪制XY軸的刻度,繪制分組標(biāo)簽,最后是繪制數(shù)據(jù)。數(shù)據(jù)項series中是分組數(shù)據(jù),它跟X軸的xAxis.data一一對應(yīng)。每個項可以自定義名稱和顏色,沒有指定的話,名稱賦予nunamed和自動生成顏色。這里還用legend屬性記錄下了標(biāo)簽列表信息,因為后續(xù)鼠標(biāo)點擊判斷是否點中用的上。

canvas主要知識點:

  1. 分組標(biāo)簽使用了arcTo方法,這樣就能繪制出圓角的效果。

  2. 繪制文本使用了measureText方法,可以用來測量文字所占寬度,這樣就可以調(diào)整下一次繪制的位置,避免位置沖突。

  3. translate位移方法,可以放在繪制上下文(save和restore的中間)中,這樣可以避免復(fù)雜的位置運算。

draw(){
    var that=this,
        ctx=this.ctx,
        canvas=this.canvas,
        W=this.W,
        H=this.H,
        padding=this.padding,
        paddingTop=this.paddingTop,
        xl=0,xs=0,xdis=W-padding*2,//x軸單位數(shù),每個單位長度,x軸總長度
        yl=0,ys=0,ydis=H-padding*2-paddingTop;//y軸單位數(shù),每個單位長度,y軸總長度

    ctx.fillStyle='hsla(0,0%,20%,1)';
    ctx.strokeStyle='hsla(0,0%,10%,1)';
    ctx.lineWidth=1;
    ctx.textAlign='center';
    ctx.textBaseLine='middle';
    ctx.font='24px arial';

    ctx.clearRect(0,0,W,H);
    if(this.title){
        ctx.save();
        ctx.textAlign='left';
        ctx.font='bold 40px arial';
        ctx.fillText(this.title,padding-50,70);
        ctx.restore();
    }
    if(this.yAxis&&this.yAxis.name){
        ctx.fillText(this.yAxis.name,padding,padding+paddingTop-30);
    }

    // x軸
    ctx.save();
    ctx.beginPath();
    ctx.translate(padding,H-padding);
    ctx.moveTo(0,0);
    ctx.lineTo(W-2*padding,0);
    ctx.stroke();
    // x軸刻度
    if(this.xAxis&&(xl=this.xAxis.data.length)){
        xs=(W-2*padding)/xl;
        this.xAxis.data.forEach((obj,i)=>{
            var x=xs*(i+1);
            ctx.moveTo(x,0);
            ctx.lineTo(x,10);
            ctx.stroke();
            ctx.fillText(obj,x-xs/2,40);
        });
    }
    ctx.restore();

    // y軸
    ctx.save();
    ctx.beginPath();
    ctx.strokeStyle='hsl(220,100%,50%)';
    ctx.translate(padding,H-padding);
    ctx.moveTo(0,0);
    ctx.lineTo(0,2*padding+paddingTop-H);
    ctx.stroke();
    ctx.restore();

    if(this.series.length){         
        var curr,txt,dim,info,item,tw=0;
        for(var i=0;i<this.series.length;i++){
            item=this.series[i];
            if(!item.data||!item.data.length){
                this.series.splice(i--,1);continue;
            }
            // 賦予沒有顏色的項
            if(!item.color){
                var hsl=i%2?180+20*i/2:20*(i-1);
                item.color='hsla('+hsl+',70%,60%,1)';
            }
            item.name=item.name||'unnamed';

            // 畫分組標(biāo)簽
            ctx.save();
            ctx.translate(padding+W/4,paddingTop+40);
            that.legend.push({
                hide:item.hide||false,
                name:item.name,
                color:item.color,
                x:padding+that.W/4+i*90+tw,
                y:paddingTop+40,
                w:60,
                h:30,
                r:5
            });
            ctx.textAlign='left';
            ctx.fillStyle=item.color;
            ctx.strokeStyle=item.color;
            roundRect(ctx,i*90+tw,0,60,30,5);
            ctx.globalAlpha=item.hide?0.3:1;
            ctx.fill();
            ctx.fillText(item.name,i*90+tw+70,26);
            tw+=ctx.measureText(item.name).width;//計算字符長度
            ctx.restore();

            if(item.hide)continue;
            //計算數(shù)據(jù)在Y軸刻度
            if(!info){
                info=calculateY(item.data.slice(0,xl));
            }
            curr=calculateY(item.data.slice(0,xl));
            if(curr.max>info.max){
                info=curr;
            }
        }

        if(!info) return;
        yl=info.num;
        ys=ydis/yl;

        //畫Y軸刻度
        ctx.save();
        ctx.fillStyle='hsl(200,100%,60%)';
        ctx.translate(padding,H-padding);
        for(var i=0;i<=yl;i++){
            ctx.beginPath();
            ctx.strokeStyle='hsl(220,100%,50%)';
            ctx.moveTo(-10,-Math.floor(ys*i));
            ctx.lineTo(0,-Math.floor(ys*i));
            ctx.stroke();

            ctx.beginPath();
            ctx.strokeStyle='hsla(0,0%,80%,1)';
            ctx.moveTo(0,-Math.floor(ys*i));
            ctx.lineTo(xdis,-Math.floor(ys*i));
            ctx.stroke();

            ctx.textAlign='right';
            dim=Math.min(Math.floor(info.step*i),info.max);
            txt=this.yAxis.formatter?this.yAxis.formatter.replace('{value}',dim):dim;
            ctx.fillText(txt,-20,-ys*i+10);
        }
        ctx.restore();
        //畫數(shù)據(jù)
        this.showData(xl,xs,info.max);
    }
}

繪制數(shù)據(jù)

因為數(shù)據(jù)項需要后續(xù)執(zhí)行動畫和鼠標(biāo)滑過的時候顯示內(nèi)容,所以把它放進動畫隊列animateArr中。這里要把分組數(shù)據(jù)展開,把之前的兩次嵌套的數(shù)組轉(zhuǎn)為一層,并計算好每個數(shù)據(jù)項的屬性,比如名稱,x坐標(biāo),y坐標(biāo),寬度,速度,顏色。數(shù)據(jù)組織完畢后,接著執(zhí)行動畫。

showData(xl,xs,max){
    //畫數(shù)據(jù)
    var that=this,
        ctx=this.ctx,
        ydis=this.H-this.padding*2-this.paddingTop,
        sl=this.series.filter(s=>!s.hide).length,
        sp=Math.max(Math.pow(10-sl,2)/3-4,5),
        w=(xs-sp*(sl+1))/sl,
        h,x,index=0;
    that.animateArr.length=0;
    // 展開數(shù)據(jù)項,填入動畫隊列
    for(var i=0,item,len=this.series.length;i<len;i++){
        item=this.series[i];
        if(item.hide)continue;
        item.data.slice(0,xl).forEach((d,j)=>{
            h=d/max*ydis;
            x=xs*j+w*index+sp*(index+1);
            that.animateArr.push({
                index:i,
                name:item.name,
                num:d,
                x:Math.round(x),
                y:1,
                w:Math.round(w),
                h:Math.floor(h+2),
                vy:Math.max(300,Math.floor(h*2))/100,
                color:item.color
            });
        });
        index++;
    }
    this.animate();
}

執(zhí)行動畫

執(zhí)行動畫也沒啥好說的,里面就是個自執(zhí)行閉包函數(shù)。動畫原理就是給y軸依次累加速度值vy。但記得當(dāng)隊列執(zhí)行完動畫后,要停止它,所以有個isStop的標(biāo)志,每次執(zhí)行完隊列的時候就判斷。

animate(){
    var that=this,
        ctx=this.ctx,
        isStop=true;
    (function run(){
        isStop=true;
        for(var i=0,item;i<that.animateArr.length;i++){
            item=that.animateArr[i];
            if(item.y-item.h>=0.1){
                item.y=item.h;
            } else {
                item.y+=item.vy;
            }
            if(item.y<item.h){
                ctx.save();
                // ctx.translate(that.padding+item.x,that.H-that.padding);
                ctx.fillStyle=item.color;
                ctx.fillRect(that.padding+item.x,that.H-that.padding-item.y,item.w,item.y);
                ctx.restore();
                isStop=false;
            }
        }
        if(isStop)return;
        requestAnimationFrame(run);
    }())
}

綁定事件

事件一:mousemove的時候,看看鼠標(biāo)位置是不是處于分組標(biāo)簽還是數(shù)據(jù)項上,繪制路徑后調(diào)用isPointInPath(x,y),true則canvas.style.cursor='pointer';如果是數(shù)據(jù)項的話,還要給把該柱形重新繪制,設(shè)置透明度,區(qū)分出來。還需要把內(nèi)容顯示出來,這里是一個相對父容器container為絕對定位的div,初始化的時候已經(jīng)建立為tip屬性了。我們把顯示部分封裝成showInfo方法。

事件二:mousedown的時候,判斷鼠標(biāo)點擊哪個分組標(biāo)簽,然后設(shè)置對應(yīng)分組數(shù)據(jù)series中的hide屬性,如果是true,表示不顯示該項,然后調(diào)用draw方法,重寫渲染繪制,執(zhí)行動畫。

bindEvent(){
        var that=this,
            canvas=this.canvas,
            ctx=this.ctx;
        this.canvas.addEventListener('mousemove',function(e){
            var isLegend=false;
                // pos=WindowToCanvas(canvas,e.clientX,e.clientY);
            var box=canvas.getBoundingClientRect();
            var pos = {
                x:e.clientX-box.left,
                y:e.clientY-box.top
            };
            // 分組標(biāo)簽
            for(var i=0,item,len=that.legend.length;i<len;i++){
                item=that.legend[i];
                ctx.save();
                roundRect(ctx,item.x,item.y,item.w,item.h,item.r);
                // 因為縮小了一倍,所以坐標(biāo)要*2
                if(ctx.isPointInPath(pos.x*2,pos.y*2)){
                    canvas.style.cursor='pointer';
                    ctx.restore();
                    isLegend=true;
                    break;
                }
                canvas.style.cursor='default';
                ctx.restore();
            }

            if(isLegend) return;
            //選擇數(shù)據(jù)項
            for(var i=0,item,len=that.animateArr.length;i<len;i++){
                item=that.animateArr[i];
                ctx.save();
                ctx.fillStyle=item.color;
                ctx.beginPath();
                ctx.rect(that.padding+item.x,that.H-that.padding-item.h,item.w,item.h);
                if(ctx.isPointInPath(pos.x*2,pos.y*2)){
                    //清空后再重新繪制透明度為0.5的圖形
                    ctx.clearRect(that.padding+item.x,that.H-that.padding-item.h,item.w,item.h);
                    ctx.globalAlpha=0.5;
                    ctx.fill();
                    canvas.style.cursor='pointer';
                    that.showInfo(pos,item);
                    ctx.restore();
                    break;
                }
                canvas.style.cursor='default';
                that.tip.style.display='none';
                ctx.globalAlpha=1;
                ctx.fill();
                ctx.restore();
            }
            
        },false);

        this.canvas.addEventListener('mousedown',function(e){
            e.preventDefault();
            var box=canvas.getBoundingClientRect();
            var pos = {
                x:e.clientX-box.left,
                y:e.clientY-box.top
            };
            for(var i=0,item,len=that.legend.length;i<len;i++){
                item=that.legend[i];
                roundRect(ctx,item.x,item.y,item.w,item.h,item.r);
                // 因為縮小了一倍,所以坐標(biāo)要*2
                if(ctx.isPointInPath(pos.x*2,pos.y*2)){
                    that.series[i].hide=!that.series[i].hide;
                    that.animateArr.length=0;
                    that.draw();
                    break;
                }
            }

        },false);
    }
    //顯示數(shù)據(jù)
    showInfo(pos,obj){
        var txt=this.yAxis.formatter?this.yAxis.formatter.replace('{value}',obj.num):obj.num;
        var box=this.canvas.getBoundingClientRect();
        var con=this.container.getBoundingClientRect();
        this.tip.innerHTML = '<p>'+obj.name+':'+txt+'</p>';
        this.tip.style.left=(pos.x+(box.left-con.left)+10)+'px';
        this.tip.style.top=(pos.y+(box.top-con.top)+10)+'px';
        this.tip.style.display='block';
    }

關(guān)于怎么在html5中使用canvas實現(xiàn)柱狀圖就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

分享題目:怎么在html5中使用canvas實現(xiàn)柱狀圖
分享URL:http://jinyejixie.com/article18/gdpodp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營銷型網(wǎng)站建設(shè)外貿(mào)建站、手機網(wǎng)站建設(shè)電子商務(wù)、響應(yīng)式網(wǎng)站、自適應(yīng)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)
泽州县| 光山县| 洪泽县| 白城市| 刚察县| 休宁县| 宜阳县| 嘉荫县| 稷山县| 沽源县| 西贡区| 桂东县| 洪洞县| 水城县| 上栗县| 西乌珠穆沁旗| 广东省| 罗田县| 军事| 固始县| 沁源县| 襄城县| 神木县| 武宁县| 钟山县| 南木林县| 扬州市| 钦州市| 西和县| 阳泉市| 崇义县| 双牌县| 庆阳市| 雅江县| 郁南县| 安乡县| 资溪县| 奈曼旗| 丹东市| 北碚区| 集贤县|