Chart.js v2: How to make tooltips always appear on pie chart?

后端 未结 5 1288
礼貌的吻别
礼貌的吻别 2020-11-27 18:49

I have found similar questions in Stack Overflow, but all of them were addressed one and two years ago. Now Chart.js has come up in version 2, and lots of the documentation

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 19:40

    Solution for ChartJs Version > 2.1.5:

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

提交回复
热议问题