如何将chartjs条形图数据值标签显示为文本?

时间:2015-03-19 15:28:18

标签: html5 html5-canvas bar-chart axis-labels chart.js

我正在使用chartjs.org创建一个条形图,我试图将垂直轴标签的值显示为文本(例如:"在性能"," ok", "好","优秀")。

请仔细检查此线框以便更好地理解。 http://i.imgur.com/HmC1vkU.png

这是我的代码。

<canvas id="barChart"  height="200"></canvas>

var barData = {
        labels: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
        datasets: [
            {
                label: "Late",
                fillColor: "rgba(3,169,244,0.5)",
                strokeColor: "rgba(3,169,244,0.8)",
                highlightFill: "rgba(3,169,244,0.75)",
                highlightStroke: "rgba(3,169,244,1)",
                data: [19, 25, 46, 77, 90, 95, 35],                 
            },
            {
                label: "My Second dataset",
                fillColor: "rgba(26,179,148,0.5)",
                strokeColor: "rgba(26,179,148,0.8)",
                highlightFill: "rgba(26,179,148,0.75)",
                highlightStroke: "rgba(26,179,148,1)",
                data: [25, 35, 55, 60, 60, 88, 15],                 
            }
        ]
    };

    var barOptions = {
        scaleBeginAtZero: true,
        scaleShowGridLines: true,
        scaleGridLineColor: "rgba(0,0,0,.05)",
        scaleGridLineWidth: 1,
        barShowStroke: true,
        barStrokeWidth: 2,
        barValueSpacing: 5,
        barDatasetSpacing: 1,
        responsive: false,
    }

   var ctx2 = document.getElementById("barChart").getContext("2d");
   window.myPieB = new Chart(ctx2).Bar(barData, barOptions);

我希望对此有一些建议。如果我需要任何东西,请告诉我。

1 个答案:

答案 0 :(得分:1)

ChartJS是一个很好但很简单的图表库。

不是修改ChartJS的源代码来显示您的自定义图例,而是使用直线和矩形在原生html画布中创建条形图可能更容易。

William Malone在这里描述了条形图做得很好:

http://www.williammalone.com/articles/html5-canvas-javascript-bar-graph/

无论您决定自定义ChartJS还是“自己滚动”,这里都是用于绘制垂直旋转的文本并以指定的X为中心的代码,Y:

enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var x=50;
var y=50;
var width=75;
var height=200;

ctx.strokeRect(x,y,width,height);

vertCenteredText(x+width*1/3,y+height/2,'Arrived On-Time');
vertCenteredText(x+width*1/2,y+height/2,'Logged-In On-Time');
vertCenteredText(x+width*2/3,y+height/2,'Tasks Completed On-Time');

function vertCenteredText(x,y,text){
  var ta=ctx.textAlign;
  var tb=ctx.textBaseline;
  ctx.translate(x,y);
  ctx.rotate(-Math.PI/2);
  ctx.textAlign='center';
  ctx.textBaseline='middle';
  ctx.fillText(text,0,0);
  // clean up by undoing our changes to canvas state
  ctx.setTransform(1,0,0,1,0,0);
  ctx.textAlign=ta;
  ctx.textBaseline=tb;
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>