Javascript: Chartjs - How to highlight "piece" of the chart when user clicks?

Asked

Viewed 299 times

2

I am working with Chart.js and my chart, type doughnut, is already cute, but I would like that, if the user click on a part of the chart the "piece" was highlighted... can be growing, staying in 3d.... Someone already did?

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();}}

Within the html:

<div data="$ctrl.data" options="$ctrl.labels">
  <canvas id="andresaChartDonutProjeto"></canvas>
  <div id="andresaChartDonutProjetoLegend" class="chart-legend"></div>
</div>
  • 1

    You can post the code of how your?

  • Felipe, what part of the code?

1 answer

3

I got!

Code working

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>
  <script src="http://www.marquei.com.br/js/Chart.min.js"></script>


</head>

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

</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.