實戰·echarts的使用
由於公司制定了開發BI資料系統的任務,而前端方面選用了echarts進行了報表的展示,下面我將使用過程中的心得與遇到的坑表述一下。
Echarts版本為echarts3.0;
專案展示圖

1553224855(1).jpg

1553225039(1).jpg
圖形中包含柱狀圖,熱力圖,餅圖,折線圖等。
不得不說echarts的功能還是很強大的,
下面我將第一幅圖的程式碼貼上來。
this.parseOption = function (data) { var chartConfig = data.chartConfig; var casted_values = data.series; var title = "" if(casted_values[0]=="cimpletesum"){ casted_values[0] ="計劃數"; casted_values[1] ="完成數"; title ="" }else{ casted_values[0] ="月總預算"; casted_values[1] ="月實際花費"; title ="" } var aggregate_data = data.data; var tunningOpt = chartConfig.option; var graphic =[]; var yearMonth =[]; var legend = {}; if(data.data ==null || data.data.length == 0 ){ title =""; graphic = [ { type: 'image', id: 'logo', left: 'center', top: '20px', z: -10, bounding: 'raw', origin: [75, 75], style: { image: '../imgs/nomore.png', width: 200, height: 120, opacity: 0.4 } }, { type: 'text', z: 100, left: 'center', top: '160px', style: { fill: '#ccc', text: [ '暫 無 數 據 喲~^o^~' ].join('\n'), font: '14px Microsoft YaHei' } } ] }else{ yearMonth =[data.keys[0][0].substr(0, 4) + '-'+data.keys[0][0].substr(5, 2)]; legend = { data: casted_values, x:'left', y:'bottom' } } var echartOption = { title : { text:title, textStyle:{ fontStyle:'normal', fontWeight:'normal', fontSize:16 }, }, legend: legend, grid: { left: '3%', right: '12%', // bottom: '3%', // height:'80%', }, graphic:graphic, calculable : true, xAxis : [ { type : 'value', boundaryGap : [0, 0.01], show: false, } ], yAxis : [ { type : 'category', data : yearMonth, show: false, } ], series : [ { name:casted_values[0], type:'bar', barGap:'-65%', barWidth: 60, label: { normal: { show: true, position:'insideTopRight', textStyle:{ color: 'white', fontSize:'14', } } }, itemStyle:{ normal: { color : '#319ee0', } }, data:_.map(aggregate_data[1]) }, { name:casted_values[1], type:'bar', barWidth: 40, label: { normal: { show: true, position:'insideRight', formatter:function(param){ if(title =="費用總覽"){ if(Number(param.value)>Number(aggregate_data[1])){ return param.value+""+"超額:"+(Number(param.value)-Number(aggregate_data[1])).toFixed(2); }else{ return param.value; } } return param.value+"("+((param.value/aggregate_data[1])*100).toFixed(2) + '%'+")" }, textStyle:{ color: 'white', fontSize:'14', } } }, itemStyle:{ normal: { color : '#52bffa' }, }, z: 5, data:_.map(aggregate_data[0]) }, ] };
其中echartOption這個物件就是echarts的核心物件,echarts通過該物件中的屬性對圖形進行處理。
其中主要屬性有
title 圖示標題 legend 圖示內容標識 grid圖示佈局 graphic 圖示的圖片填充 xAxis水平資料屬性 yAxis垂直資料屬性 series水平與垂直屬性對應的資料
其中graphic 在我的開發中起到了至關重要的作用,主要體現在,當圖示資料為空時,echarts3會預設在頁面上展示位空,是的,啥都沒有,賊醜,當然,你也可以通過div替換頁面內容,但是在我的專案中,是沒辦法替換div的,網上查詢很長時間,發現存在一個noDataLoadingOption屬性可以自動在沒資料的時候填充頁面,然鵝,當我把這個屬性放入的時候發現,根本沒有任何改變,還是空白,結果發現原來echarts3中取消了這個屬性,咋辦呢,煩躁,痛苦,終於,找到了這個屬性graphic 解決了我的問題。附上我的無資料圖。

image.png
完美解決無資料問題。graphic 的使用方式見上圖程式碼。
百度的echarts在沒接觸之前,還是覺得使用起來會比較複雜,但是使用後,發現其還是很簡單的,底層是canvas,靈活使用屬性配置就好了。