悬停在chartjs饼图上时画布填充文本消失

2022-01-22 00:00:00 canvas charts javascript chart.js

我正在使用来自 chartjs 的圆环图,在此画布的中心我填充了两行文本.这些在初始动画之后显示得很好,但是当我将鼠标悬停在甜甜圈上时,会显示相关元素的工具提示(这是预期的),但填充文本消失了.为什么会发生这种情况以及我该如何纠正它?

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 load

这是悬停后的图像

推荐答案

实际上,您可以通过简单扩展您正在使用的图表类型并将绘制代码移动到绘制覆盖内部来做到这一点

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

预览

代码

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

<小时>

小提琴 - http://jsfiddle.net/p979zyLj/

相关文章