且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-06 11:49:58

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

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):

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

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

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

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

ctx.fillText 文本到画布上,因此可以使用它来用x,y坐标写文本。你应该能够使用这种方式来做基本标签。这里是jsfiddle修补:

The ctx.fillText call 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:

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

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

如果你需要某些东西, Charts.js的版本和添加的工具提示。这里是讨论 https://github.com/nnnick/Chart.js/pull/35 ,您可以在该讨论中找到分叉版本的链接。

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.