2017-09-02 48 views
0

我使用chart.js創建堆積條形圖,並且我已成功移動並旋轉要顯示在條形頂部的x軸標籤,當我使用鼠標移過酒吧,整個圖表出現扭曲。 enter image description here工具提示將Chart.js中的條形圖弄亂

這是正常的 ,這就是我以後鼠標獲得: enter image description here

這裏是代碼

這是我用旋轉x軸標籤:

https://jsfiddle.net/staverist/zhocr17t/96/

animation: { 
         duration: 1, 
         onComplete: function() { 
         var chartInstance = this.chart; 
          var ctx = chartInstance.ctx; 
          ctx.textAlign = "left"; 
          ctx.font = "bold 10px Arial"; 
          ctx.fillStyle = "black";        
          Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) { 
            var meta = chartInstance.controller.getDatasetMeta(i); 
            Chart.helpers.each(meta.data.forEach(function (bar, index) { 
              ctx.save(); 
              // Translate 0,0 to the point you want the text 
              ctx.translate(bar._model.x, bar._model.y - 30); 
             // Rotate context by -90 degrees 
             ctx.rotate(-0.5 * Math.PI); 
                // Draw text 
           //ctx.fillText(value,0,0); 
           if(bar._datasetIndex==0){    
           ctx.fillText(bar._model.label, 0, 0); 
              ctx.restore(); 
           } 
            }),this) 
          }),this); 
        } 

回答

1

這是因爲你不是r在旋轉之後定位畫布狀態。相反,恢復它的if語句中,你應該外面恢復它,像這樣:

... 
if (bar._datasetIndex == 0) { 
    ctx.fillText(bar._model.label, 0, 0); 
} 
ctx.restore(); //<- restore canvas state 
... 

此外,你應該更好地創造一個plugin(以防止標籤閃爍),而不是在動畫完成繪製標籤。

這裏是working example on JSFiddle

相關問題