chart.js接口開發:X軸步長和Labels旋轉角


一. 當初為什么選擇chart.js

  當初項目使用庫是Zepto,Zepto能支持的chart處理庫太少。也是為了使得項目比較輕量化,所以選擇了chart.js。

  但是最后的顯示結果實在太差,放棄了char.js,還是使用jquery+highstock來完成chart需求。

 

  總而言之,項目的chart需求較低,項目要求較輕量,可以使用chart.js。

  但是,chart.js缺少幾個重要的接口,這里列出幾個。

  

二. chart.js缺少的接口

  1. x軸步長。

  bug:數值很多,x軸顯示的labels重合在一起了。

  解決方法:添加tickInterval接口

 

  找到option對象,添加tickInterval,代碼如下

var scaleOptions = {
  ...
  tickInterval : this.options.tickInterval,
  ...
}

  找到draw函數,在each下面處理,代碼如下

draw : function(){
  ...
  each(this.xLabels, function(label, index){
    ...
    ctx.lineWidth = this.lineWidth;
    ctx.strokeStyle = this.lineColor;
   // handle tickInterval
    if (this.tickInterval) {
        if (parseInt((index % this.tickInterval).toFixed(0)) !== 0) return;
    }
    ...
  }, this) 
  ...
}

  2. X軸Labels旋轉角度接口。

  Feature:x軸Label旋轉角度與數據量有關,數據量過多選裝角度很大,數據量小則旋轉角度很小。但是現實不統一,效果很差,需要統一旋轉角度。

  實現方法:添加customXLabelRota接口

 

  找到option對象,添加customXLabelRota和customXLabelRotaMinNumber,代碼如下

var scaleOptions = {
  ...
  customXLabelRota : this.options.customXLabelRota,
  customXLabelRotaMinNumber : this.options.customXLabelRotaMinNumber,
  ...
}

  找到calculateXLabelRotation函數。添加如下代碼

calculateXLabelRotation: function(){
  ...
  if ...{
    ...
    if (this.customXLabelRota && this.xLabels) {
      if (this.customXLabelRotaMinNumber) {
        if (this.customXLabelRotaMinNumber < this.xLabels.length) {
          this.xLabelRotation = this.customXLabelRota;
        }
      } else {
        this.xLabelRotation = this.customXLabelRota;
      }
    }  
  }
  else {
    ...  
  }
}

 

  3. 雙曲線時,tooltip會顯示多個

  bug描述如上,解決方法是修改tooltip顯示時添加的data,完美的解決多曲線的代碼暫時沒有完成,這里只解決雙曲線的情況,代碼如下

getPointsAtEvent : function(e){
    var pointsArray = [],
    eventPosition = helpers.getRelativePosition(e);
    helpers.each(this.datasets,function(dataset){
        helpers.each(dataset.points, function(point){
             if (point.inRange(eventPosition.x,eventPosition.y))
          pointsArray.push(point); }); },
this); // start [BugFix]: show too much tooltips if (this.datasets.length >= pointsArray.length){ return pointsArray; } if (this.datasets.length == 1){ var newPointsArray = [pointsArray[parseInt(pointsArray.length / 2)]]; }else if (this.datasets.length == 2){ var newPointsArray = [pointsArray[parseInt(pointsArray.length / 2)], pointsArray[parseInt(pointsArray.length / 2)+1]]; }else { var newPointsArray = pointsArray; } return newPointsArray // end [BugFix] //return pointsArray; },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM