ECharts畫動態儀表盤+柱狀圖(ajax獲取+循環畫圖)

出來工作幾個月了,整理下最近學的的東西。剛剛纔開通博客,第一篇就先畫儀表盤+柱狀圖。
有什麼寫的不好的地方,請大家多多指教!

jsp中首先要引用幾個文件:

<script type="text/javascript" src="../Js/ECharts/echarts.js"></script>
<script type="text/javascript" src="../JqueryCss/js/jquery.min.js"></script>
<script type="text/javascript" src="../xx/xxx.js"></script>

/xx/xxx.js 是我js代碼存放的文件。

<div id="cpu" style="width:100%;height:100%;"></div>
<div id="power" style="width:100%;height:100%;"></div>
<div id="fans" style="width:100%;height:100%;"></div>

儀表盤就畫在這個div裏面。

接下來寫js,開始畫圖了。

$(document).ready(function(){  
    refresh();  
});

用ajax提交,取值。把值放入數組中,有幾個值就畫幾個圖出來。

 function refresh(){
     $.ajax({
       type:"post",//傳遞方式,默認的時get 
       contentType: "application/x-www-form-urlencoded; charset=gb2312",  
       data:{assetID:assetID},//傳遞的參數
       url:path+"/physical.do?method=perf",//提交到哪個Action
       dataType: "json",
       success:function(data){
               var cpuList = data.cpuList;                
               var cpuArray = new Array();                 
               $.each(cpuList, function(i, n){     
                cpuArray[i]=n.item_val;                    
               });   
               refreshCPU(cpuArray);

               var powerList = data.powerList;                 
               var powerArray = new Array();                   
               $.each(powerList, function(i, n){ 
                powerArray[i]=n.item_val;   
               });
               refreshWatts(powerArray);

               var fanList = data.fanList;                 
               fans(fanList);
           }   

        }
   });
 }

先畫整個圓的儀表盤

function refreshCPU(varArray){
    var centerx;
    var size;
    var seriesArray = new Array();
    for (var i=0;i<varArray.length;i++){
    if(varArray.length<3){
        centerx = i*35+22;
        size = 70;
    }else{
        centerx = i*24+14;
        size = 55;
    }
        seriesArray.push({
                name:'溫度',
                type:'gauge',
                center : ['50%', centerx+'%'],    // 默認全局居中
                radius : size+'%',
                min:0,// 最小值
                max:80,// 最大值
                splitNumber:10,// 分割段數,默認爲5
                axisLine: {            // 座標軸線
                    lineStyle: {       // 屬性lineStyle控制線條樣式
                        color: [[0.4, 'lightgreen'],[0.6, 'orange'],[1, '#ff4500']],//設置刻度值的顏色
                        width: 3,
                        shadowColor : '#fff', //默認透明
                        shadowBlur: 10
                    }
                },
                axisLabel: {            // 座標軸小標記
                    textStyle: {       // 屬性lineStyle控制線條樣式
                        fontWeight: 'bolder',
                        color: '#000',
                        shadowColor : '#fff', //默認透明
                        shadowBlur: 10
                    }
                },
                axisTick: {            // 座標軸小標記
                    length :15,        // 屬性length控制線長
                    lineStyle: {       // 屬性lineStyle控制線條樣式
                        color: 'auto',
                        shadowColor : '#fff', //默認透明
                        shadowBlur: 10
                    }
                },
                splitLine: {           // 分隔線
                    length :25,         // 屬性length控制線長
                    lineStyle: {       // 屬性lineStyle(詳見lineStyle)控制線條樣式
                        width:3,
                        color: '#000',
                        shadowColor : '#fff', //默認透明
                        shadowBlur: 10
                    }
                },
                pointer: {           // 指針樣式 
                    shadowColor : '#fff', //默認透明
                    shadowBlur: 5
                },
                title : {//設置標題的屬性
                   offsetCenter: [0,'30%'], //標題位置
                    textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
                        fontWeight: 'bolder',
                        fontSize: 15,
                        fontStyle: 'italic',
                        color: '#000',
                        shadowColor : '#fff', //默認透明
                        shadowBlur: 10
                    }
                },
                detail : {
                    backgroundColor: '#fff',
                    borderWidth: 1,
                    borderColor: '#fff',
                    shadowColor : '#fff', //默認透明
                    width: 50,
                    height:50,
                    offsetCenter: [0, '65%'],       // x, y,單位px
                    textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
                        fontWeight: 'bolder',
                        fontSize: 20,
                        color: '#000'              
                    }
                },
                data:[{name: 'CPU'+(i+1)+'(℃)', value: varArray[i]}]
            });
    }

    var option = {
        backgroundColor: '#fff',
        tooltip : {
            formatter: "{a} <br/>{c} {b}"
        },
        grid : {  
            width : '20%' , //直角座標軸佔整頁的百分比  
            height : '100%'  
        },  
        series : seriesArray
    };  
        var myChart = echarts.init(document.getElementById("cpu"));
        myChart.setOption(option,true);// 使用剛指定的配置項和數據顯示圖表。

}

再畫半圓的儀表盤

function refreshWatts(varArray){
    var centerx;
    var size;
    var seriesArray = new Array();
    for (var i=0;i<varArray.length;i++){
    if(varArray.length<=3){
        centerx = i*30+21;
        size = 80;
    }else{
        centerx = i*22+17;
        size = 65;
    }
        seriesArray.push({
            name:'電壓',
            type:'gauge',
            center : ['50%', centerx+'%'],      // 默認全局居中
            radius : size+'%',
            min:0,
            max:400,
            startAngle:180,//開始角度
            endAngle:0,//結束角度
            splitNumber:10,
            axisLine: {            // 座標軸線
                lineStyle: {       // 屬性lineStyle控制線條樣式
                    color: [[0.29, 'lime'],[0.86, '#1e90ff'],[1, '#ff4500']],
                    width: 2,
                    shadowColor : '#fff', //默認透明
                    shadowBlur: 10
                }
            },
            axisLabel: {            // 座標軸小標記
                textStyle: {       // 屬性lineStyle控制線條樣式
                    fontWeight: 'bolder',
                    color: '#000',
                    shadowColor : '#fff', //默認透明
                    shadowBlur: 10
                }
            },
            axisTick: {            // 座標軸小標記
                length :12,        // 屬性length控制線長
                lineStyle: {       // 屬性lineStyle控制線條樣式
                    color: 'auto',
                    shadowColor : '#fff', //默認透明
                    shadowBlur: 10
                }
            },
            splitLine: {           // 分隔線
                length :20,         // 屬性length控制線長
                lineStyle: {       // 屬性lineStyle(詳見lineStyle)控制線條樣式
                    width:3,
                    color: '#000',
                    shadowColor : '#fff', //默認透明
                    shadowBlur: 10
                }
            },
            pointer: {
                width:5,
                shadowColor : '#fff', //默認透明
                shadowBlur: 5
            },
            title : {
                offsetCenter: [0, '-30%'],       // x, y,單位px
                textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
                    fontWeight: 'bolder',
                    fontStyle: 'italic',
                    color: '#000',
                    shadowColor : '#fff', //默認透明
                    shadowBlur: 10
                }
            },
            detail : {
                borderColor: '#fff',
                shadowColor : '#fff', //默認透明
                width: 80,
                height:30,
                offsetCenter: [0, '30%'],       // x, y,單位px
                textStyle: {       // 其餘屬性默認使用全局文本樣式,詳見TEXTSTYLE
                    fontWeight: 'bolder',
                    fontSize: 14,
                    color: '#000'
                }
            },

            data:[{value: varArray[i], name: '功率'+(i+1)+'(W)'}]

        });
    }

var option = {
    backgroundColor: '#fff',
    tooltip : {
        formatter: "{a} <br/>{c} {b}"
    },
    grid : {  
            width : '20%' , //直角座標軸佔整頁的百分比  
            height : '100%'  
        },  
        series : seriesArray

};     
    var myCharts = echarts.init(document.getElementById("power"));
    myCharts.setOption(option,true);// 使用剛指定的配置項和數據顯示圖表。

}

最後再畫一個柱狀圖

function fans(fanList){
    var option = {
            tooltip : {
                trigger: 'axis'
            },

             grid: {
                x: 60,
                y: 30,
                x2: 20,
                y2: 30      
            },

            calculable : true,
            xAxis : [
                {
                    type : 'category',
                    splitLine:{show: false},
                    data :(function(){  
                    var arr=[];                 
                    $.each(fanList, function(i, n){ 
                       arr.push("風扇"+(i+1));    
                    });    
                    return arr;  
                 })()               
               }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    type:'bar',
                    itemStyle:{
                        normal:{
                            color:'#4682E4',
                            label : {
                               show: true, 
                               position: 'top'
                            }
                        }

                    },
                    data :(function(){ 
                    var arr=[];
                    $.each(fanList, function(i, n){  
                       arr.push(n.item_val);
                    });    
                    return arr;
                  })()            

                }
            ]
        };

        var myChart = echarts.init(document.getElementById("fans"));
        myChart.setOption(option,true);// 使用剛指定的配置項和數據顯示圖表。

    }

Action裏面的方法

public ActionForward perf(ActionMapping map, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String jsonStr = "";
        HashMap resultMap = new HashMap();

        HostManagerDao hm = new HostManagerDao();       
        String assetID = request.getParameter("assetID");
        try{                

            ArrayList cpuList = hm.getHostData(assetID, "1");  //處理器溫度
            ArrayList powerList = hm.getHostData(assetID, "2");  //功率
            ArrayList fanList = hm.getHostData(assetID, "3");  //風扇

            resultMap.put("cpuList", cpuList);  
            resultMap.put("powerList", powerList);
            resultMap.put("fanList", fanList);

            jsonStr = CIGlobalString.getObjectToJSon(resultMap);

        }catch(Exception ex){
            ex.printStackTrace();

        }
        CIGlobalString.toPrint(request, response, jsonStr);
        return null;

    }

轉json

// 對象轉成json對象類型
    public static String getObjectToJSon(Object obj) {
        JSONObject json = JSONObject.fromObject(obj);
        return json.toString();
    }

// 集合轉成json對象類型
    public static String getListToJSon(List list) {
        JSONArray json = JSONArray.fromObject(list);
        return json.toString();
    }  

    public static void toPrint(HttpServletRequest request,
            HttpServletResponse response, String jsonStr) {
        try {
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            // System.out.println(jsonStr);
            out.print(jsonStr);
            out.flush();
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.info("對象轉換成json類型異常。");
        }

    }

截個圖給大家看看效果
這是那個整圓的儀表盤

這是半圓的儀表盤

這是畫的柱狀圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章