Как отобразить всплывающую подсказку без всплывающей круговой диаграммы с Chart.JS - PullRequest
0 голосов
/ 21 ноября 2018

enter image description here

Я использую AdminLTE и chart.js для круговых диаграмм.Вопрос в том, могу ли я сделать текст видимым для каждой дуги на круговой диаграмме, не наведя мышку?Я не использую легенды, потому что на некоторых диаграммах много меток.

Если у вас есть какие-либо другие способы показать все текстовые метки, я был бы признателен.

Это мой текущийскрипт для всех моих круговых диаграмм

<script>    
                $(function () {
                    //-------------
                    //- PIE CHART -
                    //-------------
                    // Get context with jQuery - using jQuery's .get() method.
                    var pieChartCanvas = $('#pieChart').get(0).getContext('2d')
                    var pieChart       = new Chart(pieChartCanvas)
                    var PieData        = [<?php echo $isiData; ?>]

                    var pieOptions     = {                      
                    //Boolean - Whether we should show a stroke on each segment
                    segmentShowStroke    : true,
                    //String - The colour of each segment stroke
                    segmentStrokeColor   : '#fff',
                    //Number - The width of each segment stroke
                    segmentStrokeWidth   : 2,
                    //Number - The percentage of the chart that we cut out of the middle
                    percentageInnerCutout: 0, // This is 0 for Pie charts
                    //Number - Amount of animation steps
                    animationSteps       : 150,
                    //String - Animation easing effect
                    animationEasing      : 'easeOutBack',
                    //Boolean - Whether we animate the rotation of the Doughnut
                    animateRotate        : true,
                    //Boolean - Whether we animate scaling the Doughnut from the centre
                    animateScale         : false,
                    //Boolean - whether to make the chart responsive to window resizing
                    responsive           : true,
                    // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
                    maintainAspectRatio  : true,

                    //String - A legend template
                    legendTemplate       : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'
                    }

                    //Create pie or douhnut chart
                    // You can switch between pie and douhnut using the method below.
                    pieChart.Doughnut(PieData, pieOptions)
                })  
                </script>
<canvas id="pieChart" style="height:400px;"></canvas>

Ответы [ 2 ]

0 голосов
/ 21 ноября 2018

Я использую событие onclick и модал начальной загрузки для этой проблемы и отключил всплывающую подсказку.

        ,onClick: function(c,i) {
            e = i[0];
            var x_value = this.data.labels[e._index];
            var ID = x_value;
            var Type =1;


                $.ajax({
                            url: 'getsearchresults.asmx/ChartDetayGetir',
                            data: "{ 'ID': '" + ID + "',type:'"+Type+"'}",
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            success: function (data) {

                            document.getElementById("modalheader").innerHTML = x_value;

                            document.getElementById("modalbody").innerHTML = data.d;

                            $('#myModal').modal();

                                    },
                            error: function (response) {
                                alert(response.responseText);
                            },
                            failure: function (response) {
                                alert('Failure');
                            }
                        });






        }
0 голосов
/ 21 ноября 2018

Я прекрасно провел время в Google с этой проблемой ..

По сути, другие разработчики решили вашу проблему, создав плагин, который отображает все всплывающие подсказки после рендера

Я нашел скрипку, которая решает эту проблему ..

Скрипка не моя ..

Кредиты достаются Сухайбу Джанджуа

// Show tooltips always even the stats are zero

Chart.pluginService.register({
  beforeRender: function(chart) {
    if (chart.config.options.showAllTooltips) {
      // create an array of tooltips
      // we can't use the chart tooltip because there is only one tooltip per chart
      chart.pluginTooltips = [];
      chart.config.data.datasets.forEach(function(dataset, i) {
        chart.getDatasetMeta(i).data.forEach(function(sector, j) {
          chart.pluginTooltips.push(new Chart.Tooltip({
            _chart: chart.chart,
            _chartInstance: chart,
            _data: chart.data,
            _options: chart.options.tooltips,
            _active: [sector]
          }, chart));
        });
      });

      // turn off normal tooltips
      chart.options.tooltips.enabled = false;
    }
  },
  afterDraw: function(chart, easing) {
    if (chart.config.options.showAllTooltips) {
      // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
      if (!chart.allTooltipsOnce) {
        if (easing !== 1)
          return;
        chart.allTooltipsOnce = true;
      }

      // turn on tooltips
      chart.options.tooltips.enabled = true;
      Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
        tooltip.initialize();
        tooltip.update();
        // we don't actually need this since we are not animating tooltips
        tooltip.pivot();
        tooltip.transition(easing).draw();
      });
      chart.options.tooltips.enabled = false;
    }
  }
});

// Show tooltips always even the stats are zero


var canvas = $('#myCanvas2').get(0).getContext('2d');
var doughnutChart = new Chart(canvas, {
  type: 'doughnut',
  data: {
    labels: [
      "Success",
      "Failure"
    ],
    datasets: [{
      data: [45, 9],
      backgroundColor: [
        "#1ABC9C",
        "#566573"
      ],
      hoverBackgroundColor: [
        "#148F77",
        "#273746"
      ]
    }]
  },
  options: {
    // In options, just use the following line to show all the tooltips
    showAllTooltips: true
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
     <canvas id="myCanvas2" width="350" height="296"></canvas>
</div>
...