Google饼图-图片作为标签

时间:2018-11-22 08:39:29

标签: javascript charts google-visualization

我正在使用像这样的常规Google饼图:

      google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     500],
      ['Eat',      500],
      ['Commute',  800],
      ['Watch TV', 500],
      ['Sleep',    200],
      ['Sleep',    500]
    ]);

    var options = {
      title: 'My Daily Activities'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }

但是我想在每个标签上贴一张图像。可能吗? 为了更好地解释我要搜索的内容,我添加了一张图片: enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用标签的位置-> label.getBBox()
将图片放在图表上,
在图表的'ready'事件中...

请参阅以下工作片段...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work',     500],
    ['Eat',      500],
    ['Commute',  800],
    ['Watch TV', 500],
    ['Sleep',    200],
    ['Sleep',    500]
  ]);

  var options = {
    title: 'My Daily Activities',
    legend: {
      maxLines: 2,
      position: 'top'
    },
    height: 420,
    pieSliceTextStyle: {
      color: 'transparent'
    }
  };

  var container = document.getElementById('piechart');
  var chart = new google.visualization.PieChart(container);

  google.visualization.events.addListener(chart, 'ready', function () {
    var layout = chart.getChartLayoutInterface();
    var boundsChart = layout.getChartAreaBoundingBox();

    var labels = container.getElementsByTagName('text');
    Array.prototype.forEach.call(labels, function(label) {
      if (label.getAttribute('fill') === 'none') {
        var bounds = label.getBBox();
        var whiteHat = container.appendChild(document.createElement('img'));
        whiteHat.src = 'http://findicons.com/files/icons/512/star_wars/32/clone_old.png';
        whiteHat.className = 'whiteHat';
        whiteHat.style.top = (bounds.y) + 'px';
        whiteHat.style.left = (bounds.x) + 'px';
      }
    });
  });

  chart.draw(data, options);
});
.whiteHat {
  border: none;
  position: absolute;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>