2016-11-17 48 views
0

我找到了一個Chart.js插件,它在Chart.js環形圖中寫入文本,如下所示。如何將Chart.js插件指向不同的圓環圖?

我在頁面上有兩個甜甜圈。一個叫「myChart」,一個叫「secondChart」。如果我將下面的代碼更改爲僅指向第二個圖表,則指向第二個圖表。

但是,如果我將它指向第一個圖表是在兩個圖表中呈現。有沒有辦法將這個插件變成可重用的函數,以便在頁面上的多個圖表上使用?

Chart.pluginService.register({ 
    beforeDraw: function(chart) { 
    var width = chart.chart.width, 
     height = chart.chart.height, 
     ctx = chart.chart.ctx; 

     ctx.restore(); 
     var fontSize = (height/120).toFixed(2); 
     ctx.font = fontSize + "em sans-serif"; 
     ctx.textBaseline = "middle"; 

    var text = "100%", 
     textX = Math.round((width - ctx.measureText(text).width)/2), 
     textY = height/2; 

     ctx.fillText(text, textX, textY); 
     ctx.save(); 
     } 
    }); 

回答

1

請嘗試以下代碼。經過測試和工作。希望它有助於:)

var doughnutCenterText = { 
    beforeDraw: function (chart) { 
    var width = chart.chart.width, 
    height = chart.chart.height, 
    ctx = chart.chart.ctx; 

    ctx.restore(); 
    var fontSize = (height/120).toFixed(2); 
    ctx.font = fontSize + "em sans-serif"; 
    ctx.textBaseline = "middle"; 

    var text = "100%", 
    textX = Math.round((width - ctx.measureText(text).width)/2), 
    textY = height/2; 

    ctx.fillText(text, textX, textY); 
    ctx.save(); 
     } 
    }; 

//Chart1 
    this.doughnutChart1 = new Chart(this.doughnutCanvas1.nativeElement, { 
     type: 'doughnut', 
     data: { 
      datasets: [{ 
       data: [65, 35], 
       backgroundColor: [ 
        'rgba(229, 57, 53, 1)', 
        'rgba(229, 57, 53, 0.2)', 
       ], 
       hoverBackgroundColor: [ 
        'rgba(229, 57, 53, 1)', 
        'rgba(229, 57, 53, 0.2)', 
       ], 
       hoverBorderColor: [ 
        '#fff', 
        '#fff' 
       ] 
      }] 
     }, 
     plugins: [doughnutCenterText] //Note here 
    }); 

//Chart 2 
    this.doughnutChart2 = new Chart(this.doughnutCanvas2.nativeElement, { 
     type: 'doughnut', 
     data: { 
      datasets: [{ 
       data: [55, 45], 
       backgroundColor: [ 
        'rgba(0, 137, 123, 1)', 
        'rgba(0, 137, 123, 0.2)', 
       ], 
       hoverBackgroundColor: [ 
        'rgba(0, 137, 123, 1)', 
        'rgba(0, 137, 123, 0.2)', 
       ], 
       hoverBorderColor: [ 
        '#fff', 
        '#fff' 
       ] 
      }] 
     }, 
     plugins: [doughnutCenterText] //Note here 
    });