jQuery 如何将标签添加到 Chart.js 画布插件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16590301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:25:43  来源:igfitidea点击:

How to add labels into Chart.js canvas plugin?

jquerycsscanvaschartschart.js

提问by harrison4

I'm using the awesome plugin Chart.js, and I'm trying to find the way of display labels within each percentage. So I googled it, and I found this pull: https://github.com/nnnick/Chart.js/pull/35

我正在使用很棒的插件Chart.js,我试图找到在每个百分比内显示标签的方式。所以我用谷歌搜索,我发现了这个拉:https: //github.com/nnnick/Chart.js/pull/35

I did a simple fiddle to test it, but doesn't works: http://jsfiddle.net/marianico2/7ktug/1/

我做了一个简单的小提琴来测试它,但不起作用:http: //jsfiddle.net/marianico2/7ktug/1/

This is the content:

这是内容:

HTML

HTML

<canvas id="canvas" height="450" width="450"></canvas>

JS

JS

$(document).ready(function () {
    var pieData = [{
        value: 30,
        color: "#F38630",
        label: 'HELLO',
        labelColor: 'black',
        labelFontSize: '16'
    }, {
        value: 50,
        color: "#E0E4CC"
    }, {
        value: 100,
        color: "#69D2E7"
    }];

    var myPie = new Chart(document.getElementById("canvas").getContext("2d")).Pie(pieData, {
        labelAlign: 'center'
    });
});


I'm afraid there is no information about this in the documentation.

恐怕文档中没有关于此的信息

Also I'd like to know how to display a label for each portion, but outside the chart. Linked by a line. As do the charts of highcharts.js.

另外我想知道如何为每个部分显示一个标签,但在图表之外。由一条线连接。highcharts.js的图表也是如此

By the way, I'd be glad if you recommend me an html5 chart alternative which includes the options I said above. I've heard about the flotplugin, but I'm afraid does not support animations...

顺便说一句,如果您向我推荐一个 html5 图表替代品,其中包括我上面所说的选项,我会很高兴。我听说过flot插件,但恐怕不支持动画......

If you need more info, let me know and I'll edit the post.

如果您需要更多信息,请告诉我,我会编辑帖子。

采纳答案by Hyman

You'll have to add code in 2 places. As an example, take the doughnut. First add label info to the defaults (look at the original Chart.js code and compare with this):

您必须在 2 个地方添加代码。以甜甜圈为例。首先将标签信息添加到默认值(查看原始 Chart.js 代码并与此进行比较):

    chart.Doughnut.defaults = {
        segmentShowStroke : true,
        segmentStrokeColor : "#fff",
        segmentStrokeWidth : 2,
        percentageInnerCutout : 50,
        animation : true,
        animationSteps : 100,
        animationEasing : "easeOutBounce",
        animateRotate : true,
        animateScale : false,
        onAnimationComplete : null,
        labelFontFamily : "Arial",
        labelFontStyle : "normal",
        labelFontSize : 24,
        labelFontColor : "#666"
    };

Then go down to where the Doughnut is drawn and add the four ctxlines.

然后向下到绘制甜甜圈的位置并添加ctx四行。

    animationLoop(config,null,drawPieSegments,ctx);

    function drawPieSegments (animationDecimal){
        ctx.font = config.labelFontStyle + " " + config.labelFontSize+"px " + config.labelFontFamily;
        ctx.fillStyle = 'black';
        ctx.textBaseline = 'middle';
        ctx.fillText(data[0].value + "%", width/2 - 20, width/2, 200);

The ctx.fillTextcall will put the text onto the canvas, so you can use that to write text with x,y coordinates. You ought to be able to use this way to do basic labels. Here is the jsfiddle to tinker with:

ctx.fillText调用会将文本放到画布上,因此您可以使用它来编写具有 x,y 坐标的文本。您应该能够使用这种方式来制作基本标签。这是要修补的 jsfiddle:

http://jsfiddle.net/nCFGL/(look at lines 281 and 772 in the JavaScript section of the jsfiddle for aforementioned code)

http://jsfiddle.net/nCFGL/(在 jsfiddle 的 JavaScript 部分中查看第 281 和 772 行以获得上述代码)

If you need something fancier, someone forked a version of Charts.js and added tooltips. Here is the discussion https://github.com/nnnick/Chart.js/pull/35, and you'll be able to find the link to the forked version inside that discussion.

如果您需要更高级的东西,有人会派生出一个 Charts.js 版本并添加工具提示。这是讨论https://github.com/nnnick/Chart.js/pull/35,您将能够在该讨论中找到指向分叉版本的链接。

回答by animesh manglik

This one literally took hours and hours and I found a working solution.

这个真的花了好几个小时,我找到了一个可行的解决方案。

https://github.com/nnnick/Chart.js/pull/116

https://github.com/nnnick/Chart.js/pull/116

This was my final code. I was trying to display percentages as labels on doughnut

这是我的最终代码。我试图将百分比显示为甜甜圈上的标签

Chart.types.Doughnut.extend({
name: "DoughnutAlt",
draw: function() {
    Chart.types.Doughnut.prototype.draw.apply(this, arguments);
    this.chart.ctx.fillStyle = 'black';
    this.chart.ctx.textBaseline = 'middle';
    this.chart.ctx.textAlign = 'start';
    this.chart.ctx.font="18px Verdana";

    var total = 0;
    for (var i = 0; i < this.segments.length; i++) { 
        total += this.segments[i].value;      
    }

    this.chart.ctx.fillText(total , this.chart.width / 2 - 20, this.chart.height / 2, 100);
    for(var i = 0; i < this.segments.length; i++){
        var percentage = ((this.segments[i].value / total) * 100).toFixed(1);
        if( percentage > 3 ){
            var centreAngle = this.segments[i].startAngle + ((this.segments[i].endAngle - this.segments[i].startAngle) / 2),
                rangeFromCentre = (this.segments[i].outerRadius - this.segments[i].innerRadius) / 2 + this.segments[i].innerRadius;
            var x = this.segments[i].x + (Math.cos(centreAngle) * rangeFromCentre);
            var y = this.segments[i].y + (Math.sin(centreAngle) * rangeFromCentre);
            this.chart.ctx.textAlign = 'center';
            this.chart.ctx.textBaseline = 'middle';
            this.chart.ctx.fillStyle = '#fff';
            this.chart.ctx.font = 'normal 10px Helvetica';
            this.chart.ctx.fillText(percentage , x, y);
        }
     }
}
});

回答by Sareesh

I have figured out a way so that we can display the values for each region out side the graph.

我想出了一种方法,以便我们可以在图表之外显示每个区域的值。

Also I removed the rotation of the values and I referred to here

我也删除了值的旋转,我在这里提到

Add the following lines of code inside the Doughnut function. ( I have pasted the modified lines from the Chart.js file).

在 Donut 函数中添加以下代码行。(我已经粘贴了 Chart.js 文件中修改后的行)。

    var Doughnut = function(data,config,ctx){

    var segmentTotal = 0;

    //In case we have a canvas that is not a square. Minus 10 pixels as padding round the edge.
    var doughnutRadius = Min([height/2,width/2]) - 15;
    var cutoutRadius = doughnutRadius * (config.percentageInnerCutout/100);
    //Modified for setting the label values out side the arc
    var outRadius= doughnutRadius + cutoutRadius/3;
    var outRadiustop= doughnutRadius + cutoutRadius/5;
    ......
    ......
    ......

    function drawPieSegments (animationDecimal){
    :
    :



       if (config.scaleShowValues) {
                ctx.save();                
                ctx.translate(width / 2, height / 2);
                ctx.font = config.scaleFontStyle + ' ' + config.scaleFontSize + 'px ' + config.scaleFontFamily;
                ctx.textBaselne = 'middle';
                var a = (cumulativeAngle + cumulativeAngle + segmentAngle) / 2,
                    w = ctx.measureText(data[i].value).width,
                    b = Math.PI / 2 < a && a < Math.PI * 3 / 2;
                var c  = 0 < a && a < Math.PI;
                if(b){
                    ctx.textAlign = 'right';
                }
                else{
                    ctx.textAlign = 'left';
                }
                if(c){
                    ctx.translate(Math.cos(a) * outRadius +1 , Math.sin(a) * outRadius+1);

                }
                else{
                    ctx.translate(Math.cos(a) * outRadiustop, Math.sin(a) * outRadiustop);      
                }

                ctx.fillStyle = config.scaleFontColor;
                //If the segment angle less than 0.2, then the lables will overlap, so hiding it.
                if(segmentAngle > 0.2){
                    ctx.fillText(data[i].value,0,0);

                }
                ctx.restore();
     }

     ......
     ...... 

Now the values will be displayed out side each sections and it will not be rotated.

现在这些值将显示在每个部分的外侧,并且不会旋转。

回答by dunckr

There is an forked version, ChartNew, that provides this functionality out of the box.

有一个分叉版本ChartNew,它提供了开箱即用的功能。

If you need to use ChartJS then you can use this revised version of @Hyman's solution:

如果您需要使用 ChartJS,那么您可以使用@Hyman 解决方案的修订版:

Chart.types.Doughnut.extend({
    name: "DoughnutAlt",
    draw: function() {
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);
        this.chart.ctx.fillStyle = 'black';
        this.chart.ctx.textBaseline = 'middle';
        this.chart.ctx.fillText(this.segments[0].value + "%", this.chart.width / 2 - 20, this.chart.width / 2, 200);
    }
});