2
votes

I am using a doughnut chart from chartjs, and in the center of this canvas I am filling two lines of text. These show up fine after the initial animation, but when I hover over the doughnut, a tool tip shows up for the relevant element (which is expected), but the fill text vanishes. Any reason why this might be happening and how I can rectify it ?

here is the code I am using to generate the text on the canvas

var pieChart = document.getElementById("pieChart").getContext("2d");
new Chart(pieChart).Doughnut(pieData, {percentageInnerCutout : 80, animationEasing: "easeOutQuart", onAnimationComplete: function() {
        pieChart.fillStyle = 'black'
        pieChart.font = "50px Roboto";
        pieChart.textAlign = "center";
        pieChart.fillText(distributionChartData[3]+" %", 135, 120);
        pieChart.font = "20px Roboto";
        pieChart.fillText((distributionChartData[0]+distributionChartData[1]+distributionChartData[2])+" Responses", 135, 160);
    }
});

Here is an image of the chart after initial loadenter image description here

this is the image after hoverenter image description here

3

3 Answers

2
votes

ChartJS will redraw itself as needed (for example when displaying tooltips), so you must redraw your "% and responses" text whenever ChartJS refreshes (redraws) the chart.

You can set ChartJS's 'onAnimationComplete' callback to draw your call your "% and responses" text when ChartJs has completed it's own drawing and animating.

[ Addition: ]

I've taken a look at the ChartJS source code and the Issues on Github.

There is currently no way within the ChartJS API to trigger redraws of your custom text (your "% and responses") after a tooltip closes.

One workaround would be to use CSS to place a div with your "% and responses" over the chart.

2
votes

Actually you can do this with a simple extension of the chart type you are using and moving your draw code to inside the draw override


Preview

enter image description here


Code

Chart.types.Doughnut.extend({
    name: "DoughnutAlt",
    draw: function () {
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);

        this.chart.ctx.textBaseline = "middle";
        this.chart.ctx.fillStyle = 'black'
        this.chart.ctx.font = "50px Roboto";
        this.chart.ctx.textAlign = "center";
        this.chart.ctx.fillText(distributionChartData[3] + " %", 135, 120);
        this.chart.ctx.font = "20px Roboto";
        this.chart.ctx.fillText((distributionChartData[0] + distributionChartData[1] + distributionChartData[2]) + " Responses", 135, 160);
    }
});

var pieChart = document.getElementById("pieChart").getContext("2d");
new Chart(pieChart).DoughnutAlt(pieData, {
    percentageInnerCutout: 80, animationEasing: "easeOutQuart"
});

Fiddle - http://jsfiddle.net/p979zyLj/

0
votes

I think you can set option: {animation: false} on your Chartjs settings to solve this.