将鼠标悬停在相应的图例上时突出显示饼图切片

时间:2019-08-22 07:03:58

标签: jquery chart.js

有9种饼图类型的各种相互关联的数据图表,我正在使用Chart.js库。基本上,我在循环中创建它们。数据结构就像它具有特定的颜色代码和计数一样,因此我只是在Loop中生成它们。在图例点击和其他操作上有一些ajax调用,这些刷新可以刷新图表。现在,我想要实现的是当我们将鼠标悬停在相应的图例上时突出显示饼图。我知道Chart.js中有一个onHover动作,但是如果我正在为此编写一个自定义的回调函数,我只会得到图例数据。

我尝试了onHover动作,但它很有效,但我显然不知道如何突出显示图表的各个部分。

  function genereateDataCHart(chart_type,chartData){
    return_highlights();
    $.each(chart_type, function (key, val) {
    var options = {
      responsive: true,
      title: {
        display: true,
        position: "top",
        text: key,
        fontSize: 16,
        fontColor: "#111"
      },
      legend: {
        display: true,
        position: "bottom",
        labels: {
          fontColor: "#333",
          fontSize: 10,
          generateLabels: function(chart) {
            var data = chart.data;
            if (data.labels.length && data.datasets.length) {
              var d_sum = 0;
              $.each(data.datasets[0].data,function(){d_sum+=parseInt(this) || 0;});
              return data.labels.map(function(label, i) {
                var percent = Math.round(parseInt(data.datasets[0].data[i]) * 100 / d_sum) + '%';
                return {
                  text: label + '-'+percent,
                  fillStyle: data.datasets[0].backgroundColor[i],
                  strokeStyle: data.datasets[0].borderColor[i],
                  lineWidth: 3,
                  chartTitle: key,
                  index: i
                };
              });
            }
            return [];
          },
        },
        onClick: legendCLickEvent,
      },
      tooltips: {
          enabled: false,
          custom: function(tooltipModel) {
              var tooltipEl = document.getElementById('chartjs-tooltip');
              if (!tooltipEl) {
                  tooltipEl = document.createElement('div');
                  tooltipEl.id = 'chartjs-tooltip';
                  tooltipEl.innerHTML = '<table></table>';
                  document.body.appendChild(tooltipEl);
              }
              if (tooltipModel.opacity === 0) {
                  tooltipEl.style.opacity = 0;
                  return;
              }
              // Set caret Position
              tooltipEl.classList.remove('above', 'below', 'no-transform');
              if (tooltipModel.yAlign) {
                  tooltipEl.classList.add(tooltipModel.yAlign);
              } else {
                  tooltipEl.classList.add('no-transform');
              }

              function getBody(bodyItem) {
                  return bodyItem.lines;
              }
              // Set Text
              if (tooltipModel.body) {
                  var bodyLines = tooltipModel.body.map(getBody);
                  var check = bodyLines[0][0].split(':');
                  var tt_data = chartData[key]['tooltip'][check[0]];
                  var innerHtml = '<thead><tr>';
                  $.each(tt_data, function(type,titles) {
                    innerHtml += '<th style="color:white;">'+check[0]+' '+type+' - '+titles.length+'</th>';
                  });
                  innerHtml += '</tr></thead><tbody><tr>';
                  $.each(tt_data,function(key, values) {
                      innerHtml += '<td><ul style="list-style:none;color:white;">';
                      $.each(values, function(k, v){
                        innerHtml += '<li style="padding-left:none;">';
                        innerHtml += v;
                        innerHtml += '</li>';
                      });
                      innerHtml += '</ul></td>';
                  });
                  innerHtml += '</tr></tbody>';

                  var tableRoot = tooltipEl.querySelector('table');
                  tableRoot.innerHTML = innerHtml;
              }
              var position = this._chart.canvas.getBoundingClientRect();
              tooltipEl.style.opacity = 1;
              tooltipEl.style.background = 'rgba(0,0,0,0.8)';
              tooltipEl.style.position = 'absolute';
              // tooltipEl.style.left = '40%';
              tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
              tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
              tooltipEl.style.fontFamily = tooltipModel._bodyFontFamily;
              tooltipEl.style.fontSize = tooltipModel.bodyFontSize + 'px';
              tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle;
              tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px';
              tooltipEl.style.pointerEvents = 'none';
          }
        }
    };

    var data = {
      labels: chartData[key]['labels'],
      datasets: [
        {
          label: chartData[key]['title'],
          data: chartData[key]['data'],
          backgroundColor:  chartData[key]['colours'],
          borderColor: "#fff",
          borderWidth: 1,
        }
      ]
    };

    var chart = new Chart(val[0], {
        type: val[1],
        data: data,
        options: options
      });
      chartID.push(chart);
    });

}
//FYI - custom legend click callback
var legendCLickEvent = function (e, legendItem) {
      var status = [];
      if ($('#active-check').is(':checked')){
          status.push('Acquired');
      };

      if ($('#listed-check').is(':checked')){
          status.push('Approved');
      };
      if ($('#pipe-check').is(':checked')){
          status.push('Shortlisted');
      };
      var chartTitle = legendItem.chartTitle;
      var labelText = legendItem.text;
      var filter = labelText.split('-');
      show_filters(chartTitle);
      show_filters(filter[0]);
      var ids = returnSelectedIds();
      $.ajaxSetup({
            headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
      $.ajax({
          method: "POST",
          url: "{{url('content-charts')}}",
          data: {action:'content-chart-ajax-label',ids:ids,chartTitle:chartTitle, labelText:labelText, status:status},
          success:function(response){
            $.each(chartID, function(key, chart){
                chart.destroy();
            });
            var chartData = JSON.parse(response);
            genereateDataCHart(chart_type,chartData);
          },
          error:function(xhr, status, error){
            handleAjaxError(xhr);
          }
      });
  };

如果可以通过某些参数(例如容器ID,数据索引,图表标题)突出显示切片,因为在为onHover创建自定义回调函数时,我只会得到legendItem数据。 Chart.js版本为2.4.0

0 个答案:

没有答案