簡體   English   中英

使用ChartJS問題在甜甜圈中間繪制餅圖段百分比

[英]Drawing pie segment percentage in middle of doughnut with chartjs issue

我正在嘗試繪制當前在甜甜圈中間懸停的甜甜圈部分的百分比。

我正在使用chartjs 2,因此正在研究插件。 在文檔中說,有一次可以在“ afterEvent”上調用插件-“在畫布上發生事件時(mousemove,click等)。這需要處理options.events屬性”。 頁面上的代碼如下:

afterEvent: function(chartInstance, event) {}

但是,我不確定如何使用afterEvent狀態。 通過遵循這樣的例子我可以靜態地在甜甜圈的中間畫畫。 但是我希望能夠在“ afterEvent”而不是“ beforeDraw”上運行此代碼。 是否有關於“ event”參數中包含哪些事件數據的文檔? 如果這是一個懸停事件,是否會像“ onHover”一樣給我懸停的細分的價值?

我只是在任何地方都找不到其他文檔。 如果有人能指出我正確的方向,那就太好了。

謝謝你的時間。

最有可能通過插件來實現這一點,但是這是另一種方法,可以為您提供完全相同的行為。

基本上,您使用一個外部自定義工具提示,該提示位於圖表中間,當懸停圖表細分時會觸發該提示。

這是相關的代碼

Chart.defaults.global.tooltips.custom = function(tooltip) {
  // Tooltip Element
  var tooltipEl = document.getElementById('chartjs-tooltip');

  // Hide if no tooltip
  if (tooltip.opacity === 0) {
    tooltipEl.style.opacity = 0;
    return;
  }

  // Set Text
  if (tooltip.body) {
    var total = 0;

    // get the value of the datapoint
    var value = this._data.datasets[tooltip.dataPoints[0].datasetIndex].data[tooltip.dataPoints[0].index].toLocaleString();

    // calculate value of all datapoints
  this._data.datasets[tooltip.dataPoints[0].datasetIndex].data.forEach(function(e) {
      total += e;
    });

    // calculate percentage and set tooltip value
    tooltipEl.innerHTML = '<h1>' + (value / total * 100) + '%</h1>';
  }

  // calculate position of tooltip
  var centerX = (this._chartInstance.chartArea.left + this._chartInstance.chartArea.right) / 2;
  var centerY = ((this._chartInstance.chartArea.top + this._chartInstance.chartArea.bottom) / 2);

  // Display, position, and set styles for font
  tooltipEl.style.opacity = 1;
  tooltipEl.style.left = centerX + 'px';
  tooltipEl.style.top = centerY + 'px';
  tooltipEl.style.fontFamily = tooltip._fontFamily;
  tooltipEl.style.fontSize = tooltip.fontSize;
  tooltipEl.style.fontStyle = tooltip._fontStyle;
  tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
};

還有一個可行的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM