Javascript: ChartJS - How to highlight "piece" of the graph when user clicks?

2

I'm working with Chart.js and my donut chart is already cute, but I would like that if the user clicks on a part of the graph the "piece" is highlighted ... it can be growing, getting in 3d Has anyone done?

As requested, follow the code: controller (angularJs):

function andresaChartDonutProjetoController($http,$element, $attrs){
//variaveis
var vm = this;
vm.type = 'doughnut';
vm.myLabels=[];
vm.myValues=[];
var total = 0;
var textTotal;
//funçoes
vm.listarProjeto = listarProjeto();

function listarProjeto(){

        vm.dados = [];
        vm.dados = [

            {
                "codigo": 1,
                "label": " ICMS",
                "porcentagem": 30,
                "valor": 30000,
            "base": "#FF0000",
            "light": "#FF3C3C"
            }, {
                "codigo": 2,
                "label": " IR ",
                "porcentagem": 15,
                "valor": 15000,
            "base": "#9E3534",
            "light": "#C85959"
            }, {
                "codigo": 3,
                "label": " ICC",
                "porcentagem": 25,
                "valor": 25000,
            "base": "#FF8000",
            "light": "#FFA953"
            }, {
                "codigo": 4,
                "label": " IPGM",
                "porcentagem": 20,
                "valor": 20000,
            "base": "rgba(75, 192, 192, 0.2)",
            "light": "rgba(153, 102, 255, 0.2)"
            }, {
                "codigo": 5,
                "label": " Outros",
                "porcentagem": 10,
                "valor": 10000,
            "base": "rgba(255, 206, 86, 0.2)",
            "light": "rgba(54, 162, 235, 0.2)"
            }
        ]
        angular.forEach(vm.dados, function(item){
          vm.myLabels.push(item.label);
          vm.myValues.push(item.valor);
                    total+=item.valor;
        });
        textTotal = total+" Total"
        gerarGrafico();


  }

function gerarGrafico(){

  vm.data = {
                       labels:vm.myLabels,
                       datasets: [
                           {
                              data: vm.myValues,
                              backgroundColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],
                              hoverBackgroundColor:[
                                                       'rgba(255, 99, 132, 0.2)',
                                                       'rgba(54, 162, 235, 0.2)',
                                                       'rgba(255, 206, 86, 0.2)',
                                                       'rgba(75, 192, 192, 0.2)',
                                                       'rgba(153, 102, 255, 0.2)',
                                                       'rgba(255, 159, 64, 0.2)'
                                                   ]
                           }]
                   };
     vm.options = {
                       cutoutPercentage: 74,
                       responsive:true,

                        legend: {
                          display: false,
                          responsive: false
                        },
                        tooltips: {
                          callbacks: {
                            label: function(tooltipItem, data) {
                              return (vm.dados[tooltipItem.index].porcentagem+"%").replace('.',',');
                            }
                          }
                        }


                       ///


                    };
  var ctx = document.getElementById("andresaChartDonutProjeto").getContext("2d");



  var myChart = new Chart(ctx, {
    type:vm.type,
    data: vm.data,
    options: vm.options
  });

/////
Chart.pluginService.register({
beforeDraw: function(myChart) {


  var width = myChart.chart.width,
  height = myChart.chart.height,
  ctx = myChart.chart.ctx,
  type = myChart.config.type;

  if (type == 'doughnut')
  {
/*Primeiro Texto dentro do gráfico*/
    var fontSize = 1.5; //fonte do texto interno
    ctx.restore();
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "middle"

  var   value = textTotal;

    var text = value,
    textX = Math.round((width - ctx.measureText(text).width) / 2),
    textY = (height + myChart.chartArea.top) / 2;

    ctx.clearRect(textX - 10, textY - 10, 0, 35);

    ctx.fillStyle =  'black';
    ctx.fillText(text, textX, textY);
    ctx.save();


  }
}
});

/////


  document.getElementById('andresaChartDonutProjetoLegend').innerHTML = myChart.generateLegend();}}

Inside the html:

<div data="$ctrl.data" options="$ctrl.labels">
  <canvas id="andresaChartDonutProjeto"></canvas>
  <div id="andresaChartDonutProjetoLegend" class="chart-legend"></div>
</div>
    
asked by anonymous 10.11.2016 / 19:59

1 answer

3

I did it!

Working Code

function GraficoController($http, $element, $attrs) {

  var vm = this;

  vm.myLabels = [];
  vm.myValues = [];
  vm.myHoverColor = [];
  vm.myForteColor = [];
  //funçoes
  vm.listarProjeto = listarProjeto();

  function listarProjeto() {

    vm.dados = [];
    vm.dados = [

      {
        "codigo": 1,
        "label": " Brasília",
        "porcentagem": 30,
        "valor": 30000,
        "base": "#FF0000",
        "light": "#FF3C3C",
        "dark": "#800080"
      }, {
        "codigo": 2,
        "label": " São Paulo ",
        "porcentagem": 15,
        "valor": 15000,
        "base": "#9E3534",
        "light": "#C85959"
      }, {
        "codigo": 3,
        "label": " Rio de Janeiro",
        "porcentagem": 25,
        "valor": 25000,
        "base": "#FF8000",
        "light": "#FFA953"
      }, {
        "codigo": 4,
        "label": " Outros",
        "porcentagem": 20,
        "valor": 20000,
        "base": "rgba(75, 192, 192, 0.2)",
        "light": "rgba(153, 102, 255, 0.2)"
      }
    ]
    angular.forEach(vm.dados, function(item) {
      vm.myLabels.push(item.label);
      vm.myValues.push(item.valor);
      vm.myHoverColor.push(item.light);
      vm.myForteColor.push(item.base);

    });

    gerarGrafico();


  }

  function gerarGrafico() {

    vm.data = {
      labels: vm.myLabels,
      datasets: [{
        data: vm.myValues,
        backgroundColor: [
          'rgba(255,99,132,1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)'
        ],
        borderColor: [
          'rgba(255,255,255,1)',
          'rgba(255,255,255,1)',
          'rgba(255,255,255,1)',
          'rgba(255,255,255,1)',
          'rgba(255,255,255,1)'
        ],
        borderWidth: 1,
        hoverBackgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ]
      }]
    };
    vm.options = {
      cutoutPercentage: 70,
      responsive: true,

      legend: {
        display: false,
        responsive: false
      }


    };
    var ctx = document.getElementById("andresaProjeto").getContext("2d");

    vm.myChart = new Chart(ctx, {
      type: 'doughnut',
      data: vm.data,
      options: vm.options
    });

    document.getElementById("andresaProjeto").onclick = function(evt) {

      activePoints = vm.myChart.getElementsAtEvent(evt);
      if (activePoints.length == 1) {
        var indice = activePoints[0]["_index"];
        var contador = 0;

        angular.forEach(vm.dados, function(item) {
          if (contador != indice) {
            vm.myChart.config.data.datasets[0].backgroundColor[contador] = vm.myHoverColor[contador];
            vm.myChart.config.data.datasets[0].borderColor[contador] = 'rgba(255,255,255,1)';
            vm.myChart.config.data.datasets[0].hoverBackgroundColor[contador] = vm.myHoverColor[contador];
            vm.myChart.config.data.datasets[0].borderWidth = 1;
            vm.myChart.render();
          }

          contador++;
        });

        vm.myChart.config.data.datasets[0].backgroundColor[indice] = vm.myForteColor[indice];
        vm.myChart.config.data.datasets[0].borderColor[indice] = vm.myForteColor[indice];
        vm.myChart.config.data.datasets[0].hoverBackgroundColor[indice] = vm.myForteColor[indice];
        vm.myChart.config.data.datasets[0].borderWidth = 10;

        vm.myChart.render();
        vm.myChart.update();

      }


    }



  }
}
<html ng-app>

<head>
  <title>Gráfico</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script><scriptsrc="http://www.marquei.com.br/js/Chart.min.js"></script>


</head>

<body ng-controller="GraficoController">
  <div>
    <canvas id="andresaProjeto"></canvas>
  </div>
</body>

</html>
    
29.11.2016 / 22:35