1. 程式人生 > >Highcharts,Highslide常用方法屬性介紹

Highcharts,Highslide常用方法屬性介紹

在做資料報表時候,由於其相容性好,功能強大,Highcharts外掛是比較好的選擇。Highcharts支援大部分的圖表型別:直線圖,曲線圖、區域圖、區域曲線圖、柱狀圖、餅裝圖、散佈圖等等,並且對PC/Tablet/Phone的各種瀏覽器都支援的很好。下面結合專案說說Highcharts常用的方法和屬性。

Highcharts作為名稱空間,其下包括一個變數的集合。我們通常這樣來定義一個全域性的圖表物件,示例化Highcharts物件的同時進行命名。

var hc = new Highcharts.Chart(options);

以下方法或屬性的呼叫方式是Highcharts.MethodOrPropertises

Highcharts常用方法或屬性:

1.Chart方法Chart (Object options, Function callback)

本方法作為建立圖表物件的建構函式,包括兩個引數,在IE8以下,有時圖表初始化時文件還沒有完全載入完成,圖表物件還沒有建立完成,會造成一些影響。因而,依賴於圖表物件的程式碼應該寫在回撥函式中,同樣效果的做法是使用chart.event.load。

2.charts屬性

返回值為當前頁面所有的圖表物件陣列。

3.dateFormat (String format, [Number time], [Boolean capitalize])

將一個javascript時間戳(毫秒)轉為可讀性的日期時間串。time引數為js數字時間串,capitalize引數規定返回值是否要首字母大寫,format引數可以參考PHP手冊中關於函式strftime()的介紹。

4.dateFormats

此描述符用於定義系統未提供的日期格式,一般以key:value形式定義,描述符作為key,定義一個函式作為value,該函式根據自身需要返回目標日期格式。
例如:
    /**
     * Add custom date formats
     */
    Highcharts.dateFormats = {
        W: function (timestamp) {
            var date = new Date(timestamp),
                day = date.getUTCDay() == 0 ? 7 : date.getUTCDay(),
                dayNumber;
            date.setDate(date.getUTCDate() + 4 - day);
            dayNumber = Math.floor((date.getTime() - new Date(date.getUTCFullYear(), 0, 1, -6)) / 86400000);
            return 1 + Math.floor(dayNumber / 7);
            
        }
    }

5.numberFormat (Number number, [Number decimals], [String decimalPoint], [String thousandsSep])

該方法生成一個格式化的js數字串,函式可以接收一個、兩個、四個引數,而不可以是三個。number引數是要加工的數字,decimals是小數的位數,decimalPoint規定用什麼字元作為小數點,thousandsSep字元作為千分符。PHP中也有以此名字命名的函式number_format(),如果需要更多瞭解可以參照php手冊。

PHP的函式宣告格式:

string number_format ( float $number [, int $decimals = 0 ] )
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

6.setOptions (Object options)

呼叫此方法,會給所有建立的圖表都設定options。例如:
    Highcharts.setOptions({
        colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
        chart: {
            backgroundColor: {
                linearGradient: [0, 0, 500, 500],
                stops: [
                    [0, 'rgb(255, 255, 255)'],
                    [1, 'rgb(240, 240, 255)']
                ]
            }
    ,
            borderWidth: 2,
            plotBackgroundColor: 'rgba(255, 255, 255, .9)',
            plotShadow: true,
            plotBorderWidth: 1
        },
    //……
    }

或者

Highcharts.setOptions({global:{useUTC : false}});  

其中,如果用到顏色取值,可以來這個網址進行對應。http://www.w3school.com.cn/html/html_colorsfull.asp

Highslide方法hs.htmlExpand(),hs.expand()可以參考官方文件,點選檢視http://www.highslide.com/ref/hs.expand

hs.htmlExpand函式
作為hs.expand 的一個特例,是建立一個包含HTML內容的擴充套件器,而不是hs.expand函式的圖片內容。在遇到Ajax,Iframe和Flash內容時,hs.htmlExpand才能體現其價值所在,可以將擴充套件內容加工處理寫進目標內容區域。

其原型為:boolean hs.htmlExpand( DOMElement element [, Object overrides [, Object custom]] )

hs.expand 函式的原型:boolean hs.expand( DOMElement element [, Object overrides [, Object custom]] )
該函式一般用於單擊彈出一個內建小圖的大圖,背後邏輯當單擊事件返回true,則彈出行為觸發,若彈出成功,返回false,彈出失敗,返回true。預設行為是開啟href屬性指向的圖片。該方法的第二、第三個引數用於定製符合使用者需求的圖片彈出效果。

//用法例項1
<a class="highslide" href="../samples/full3.jpg"
      onclick="return hs.expand(this,
      { outlineType: 'rounded-white', targetX: 'thumb1' })">
   <img src="../samples/thumb3.jpg" alt=""/>
</a>
//用法例項2
<a class="highslide" href="../samples/full3.jpg" onclick="return hs.expand(this, null,
      { myAlert: 'This is a custom variable' } )">
   <img src="../samples/thumb3.jpg" alt=""/>
</a>
//用法例項3
hs.expand(null, {
    src: 'image1.jpg'
});
//用法例項4
<div class="highslide-caption">
   <h1 onclick="alert(hs.getExpander(this).custom.myAlert)">Click me</h1>
</div>
//用法例項5
<a class="highslide" href="../samples/full3.jpg"
      onclick="return hs.expand(this, null, { foo: 'Happy', bar: 'coding' } )">
   <img src="../samples/thumb3.jpg" alt=""/>
</a>
<div class="highslide-caption">
  The Highslide author says "{foo} {bar}!"
</div>


部分常用API介紹:

Chart:圖表區選項
---------------------

renderTo 引用容器,html中放置圖表的容器,html設定該DIV的id屬性值
borderWidth 設定圖表邊框寬度
borderRadius 設定圖表邊框圓角角度
backgroundColor 設定圖表區背景色
className 確定繪圖區容器的類區範圍
defaultSeriesType 預設繪圖型別的設定
events繪圖觸發事件
addSeries 新增series資料
click 該函式定義單擊事件
load 該函式定義載入事件
redraw 該函式定義重畫事件
selection 該函式定義選著區域事件
type 繪圖型別 預設:line
width 繪圖寬度的設定
height高度
ignoreHiddenSeries多個數據時,隱藏一個數據是否更改軸心,預設true為可更改
inverted 數軸的轉換預設false
margin 內邊距設定
marginTop
marginBottom
marginLeft
marginRight
plotBackgroundColor部分顏色的變化
plotBackgroundImage 載入圖片
plotBorderColor
plotBorderWidth
plotBorderShadow
reflow  是否跟誰容器大小改變
resetZoonButton 區域選擇與重置圖片與event事件中的selection事件相似
selectionMarkerFill 懸著區域的顏色
shadow陰影
showAxes 載入前軸的顯示
spacingTop 外邊距
spacingBottom
spacingLeft
style 設定CSS樣式,駝峰寫法
zoomType 區域選擇範圍   可與event.selection和resetZoomButton參考,他們是區域選擇的功能介面
----------------------------
credits 右下角的名片說明

enabled 預設值true顯示名片
position 位置的確定
href 名片連線地址   預設值:www.highcharts.com
style 名片CSS樣式
text 名片顯示的文字  預設值:highcharts.com
-----------------------
global  Highcharts.SetOptions方法呼叫

canvasToolsURL 畫布工具連線,例如:Andrio的 2.0不支援SVG
useUTC    是否使用UTC time 
---------------------------
xAxis:yAxis: X和Y座標軸的引數

gridLineColor 網格顏色
reversed 是否反向/轉置座標系 true ,false
gridLineWidth 網格粗細
startOnTick 是否從座標線開始畫圖區域
endOnTick 是否從座標線結束畫圖區域
tickmarkPlacement 座標值與座標線標記的對齊方式on,between
tickPosition 座標線標記的樣式 向內延伸還是向外延伸(insidel,outside)
tickPixelInterval 決定著橫座標的密度
tickColor 座標線標記的顏色
tickWidth 座標線標記的寬度
lineColor 基線顏色
lineWidth 基線寬度
max 固定座標最大值
min 固定座標最小值
plotlines 標線屬性
maxZoom
minorGridLineColor
minorGridLineWidth
minorTickColor
-----------------
title 標題屬性

enabled: 是否顯示
text: 座標名稱
Labels 座標軸值顯示類 預設:defaultLabelOptions
formatter 格式化函式
enabled 是否顯示座標軸的座標值
rotation 傾斜角度
align 與座標線的水平相對位置
x 水平偏移量
y 垂直偏移量
style 設定CSS樣式
font 字型樣式 預設defaultFont
color 字型顏色
---------------------
Tooltip 資料點的提示框

enabled 滑鼠經過時是否可動態呈現true,false
formatter 格式化提示框的內容樣式

---------------------------
plotOptions 畫各種圖表的資料點的設定

Area類:
lineWidth 線寬度
fillColor area的填充顏色組
marker{} 設定動態屬性
shadow 是否陰影 true,false
states 設定狀態
Line類
dataLabels: 資料顯示類
enabled 是否直接顯示點的資料true,false
--------------------------------
colors 顏色設定
用於展示圖表,折線/柱狀/餅狀等圖的顏色,陣列形式。
--------------------------------
Legend:圖例選項
layout 顯示形式,支援水平horizontal和垂直vertical,預設horizontal
align對齊方式。預設center
backgroundColor圖例背景色。
borderColor圖例邊框顏色,預設#909090
borderRadius圖例邊框角度
enabled 是否顯示圖例
floating是否可以浮動,配合x,y屬性。 預設不顯示
shadow 預設不顯示陰影
style 設定圖例內容樣式
---------------------------
Navigation按鈕和圖例選項

buttonOptions設定匯出,列印按鈕的選項,如顯示的位置,樣式,是否啟用等
menuItemHoverStyle懸停在圖例上面的樣式
menuItemStyle 樣式
mentStyle 設定樣式
----------------------------
Loading 在圖形上顯示loading文字

hideDuration 設定loading標籤淡出的時間,預設100
showDuration 設定loading標籤淡入的時間,預設100
labelStyle 是Loading標籤樣式
style 設定樣式,涵蓋了繪圖區
----------------------------
series 資料列

name 該條曲線名稱
data[] 該條曲線的資料項
addPoint([x,y],redraw,cover) 新增描點,redraw 是否重畫,cover是否左移
setData: function(data, redraw) 重新設定Data陣列,redraw是否重畫
remove: function(redraw) 刪除曲線
redraw: function() 重畫曲線
marker :標記點
enabled 是否顯示描點

最後,專案報表需要,這裡列出自己專案的js程式碼,分享。使用了上面的Highchart。jQuery和Ajax。

<script type="text/javascript" src="./static/js/jquery.min.js"></script>
<script type="text/javascript">
	$(function () {
        // define the options
        var options = {

            chart: {
				renderTo: 'container',  
				type: 'line',  
				events: {  
					load: function (event) {  
						for (var i = this.series.length - 3; i > 1; i--) {  
							this.series[i].hide();        //設定只顯示其中四條線,其他都不顯示  
						}  
					}  
				}  
            },

            title: {
                text: 'iOS月報表—資料走勢圖',
		margin: 15
            },

            subtitle: {
                text: ''
            },

            xAxis: {
				title: {
					text: '時間',
					style: {
						color: '#C00',
						fontWeight: 'bold'
					}
				},
				type:'category',
                tickWidth: 2,
				gridLineWidth: 0,
				lineWidth:2,
                labels: {
                    align: 'center',
                }
            },

            yAxis: [{ // left y axis
                title: {
                    text: '人/次',
			style: {
				color: '#C00',
				fontWeight: 'bold'
			}
                },
                labels: {
                    align: 'left',
                    x: 3,
                    y: 16,
                    formatter: function() {
                        return Highcharts.numberFormat(this.value, 0);
                    }
                },
                showFirstLabel: false
            }, { // right y axis
                linkedTo: 0,
                gridLineWidth: 0,
                opposite: true,
                title: {
                    text: null
                },
                labels: {
                    align: 'right',
                    x: -3,
                    y: 16,
                    formatter: function() {
                        return Highcharts.numberFormat(this.value, 0);
                    }
                },
                showFirstLabel: false
            }],

            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -10,
                y: 70,
                borderWidth: 0,
				itemMarginTop: 5,
				itemMarginBottom: 5
            },

            tooltip: {
                shared: true,
                crosshairs: true,
				style: {
					fontSize: '11px',
					fontFamily: 'tahoma,arial,simSun,Microsoft Yahei'
				}
            },

            plotOptions: {
                series: {
                    cursor: 'pointer',
					allowPointSelect: true,
                    point: {
                        events: {
                            click: function() {
                                hs.htmlExpand(null, {
                                    pageOrigin: {
                                        x: this.pageX,//定義彈窗的橫座標
                                        y: this.pageY
                                    },
                                    headingText: this.series.name,
                                    //maincontentText: this.category + ': '+ this.y +' 人/次',
                                    maincontentText: this.category.substring(0,4) + '年' + this.category.substring(5,7) + '月' + ': '+ this.y +' 人/次',
                                    width: 200
                                });
                                /*
                                hs.htmlExpand(null, {
                                    pageOrigin: {
                                        x: this.pageX,
                                        y: this.pageY
                                    },
                                    headingText: this.series.name,
                                    maincontentText: Highcharts.dateFormat('%Y, %b %e, %Y', this.x) +':<br/> '+
                                        this.y +' visits',
                                    width: 200
                                });
                                */
                            }
                        }
                    },
                    marker: {
                        lineWidth: 1
                    }
                }
            },
			credits: {    
                enabled: true,     //是否顯示網站標誌如url  
		href: 'http://www.feiliu.com',//預設highcharts網站的url
		text: 'Powered by Feiliu'
            },
            series: [{
                name: '新增使用者數',
                lineWidth: 4,
                marker: {
                    radius: 4
                }
            }, {
                name: '註冊/繫結使用者數'
            }, {
                name: '聯網使用者數'
            }, {
                name: '聯網次數'
            }, {
                name: '下載次數'
            }, {
                name: '下載人數'
            }]
        };


        // Load data asynchronously using jQuery. On success, add the data
        // to the options and initiate the chart.
        // This data is obtained by exporting a GA custom report to TSV.
	//GA = Google analytics 是谷歌公司的一款免費企業級分析軟體,任何人都可以免費註冊使用。軟體的特點是電子商務功能。GA自定義報告
        // http://api.jquery.com/jQuery.get/
		var datestart = document.getElementById("monthstart").innerHTML;
		var dateend = document.getElementById("monthend").innerHTML;
        jQuery.get('http://pmtest.feiliu.com/?c=ptd&a=monthchart', {timestart:datestart,timeend:dateend}, function(data, state, xhr) {
            var records = [],
                date,
                // set up the data series
				allDate = [],
                newUsers = [],
                regUsers = [],
				connUsers = [],
				connTimes = [],
				dlTimes = [],
				dlUsers = [];
            // inconsistency
            if (typeof data !== 'string') {
                data = xhr.responseText;
            }
            // split the data return into lines and parse them
			data = eval('(' + data + ')');
            jQuery.each(data, function(i, record) {
                // all data records start with a double quote
				date = record.monthnm;
				newUsers.push([
					date,
					parseInt(record.newuser, 10)
				]);
				regUsers.push([
					date,
					parseInt(record.reguser)
				]);
				connUsers.push([
					date,
					parseInt(record.connuser)
				]);
				connTimes.push([
					date,
					parseInt(record.conntime)
				]);
				dlTimes.push([
					date,
					parseInt(record.dltime)
				]);
				dlUsers.push([
					date,
					parseInt(record.dluser)
				]);
				allDate.push(date);
            });
            options.series[0].data = newUsers;
            options.series[1].data = regUsers;
            options.series[2].data = connUsers;
            options.series[3].data = connTimes;
            options.series[4].data = dlTimes;
            options.series[5].data = dlUsers;
            options.xAxis.categories = allDate;
            //兩種方式,或者也可下面這樣設定
            //Highcharts.setOptions({xAxis: {categories: allDate}});
            $('#container').highcharts(options);
        });
    });
</script>