2016-05-13 80 views
1

我需要使用chart.js之文本里面吧 - chart.js之

var ctx = document.getElementById("myChart"); 
     var myChart = new Chart(ctx, { 
      type: 'bar', 
      data:data, 
      options: { 

       scales: { 
        yAxes: [{ 
         ticks: { 
          beginAtZero:true 
         } 
        }] 
       } 
      }, 
      responsive : true, 
      showTooltips : false, 
      showInlineValues : true, 
      centeredInllineValues : true, 
      tooltipCaretSize : 0, 
      tooltipTemplate : "<%= value %>" 
     }); 

上面的代码不工作,写文成酒吧表...

我需要的是这样的:

example

回答

2

你有一个 var ctx = document.getElementById("myChart");在你的代码中定义。

UPDATE

这个代码添加到你的选择对象:

animation: { 
    onComplete: function() { 
    var chartInstance = this.chart; 
    var ctx = chartInstance.ctx; 
    console.log(chartInstance); 
    var height = chartInstance.controller.boxes[0].bottom; 
    ctx.textAlign = "center"; 
    Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) { 
     var meta = chartInstance.controller.getDatasetMeta(i); 
     Chart.helpers.each(meta.data.forEach(function (bar, index) { 
     ctx.fillText(dataset.data[index], bar._model.x, height - ((height - bar._model.y)/2)); 
     }),this) 
    }),this); 
    } 
} 

https://jsfiddle.net/h4p8f5xL/

UPDATE 2

环绕与容器画布以所需的宽度和高度

<div style="width: 100%; height: 500px"> 
    <canvas id="myChart" width="400" height="400"></canvas> 
</div> 

,并添加以下到您的选项对象

// Boolean - whether or not the chart should be responsive and resize when the browser does. 
responsive: true, 
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container 
maintainAspectRatio: false, 
+0

是的...它的我的画布标签 – novato

+0

你能告诉我们控制台输出? – torresomar

+0

控制台输出?你的意思是图表? – novato

1

如果你想使居中文本的每个元素,还有一个更简单的方法:

Chart.helpers.each(meta.data.forEach(function (bar, index) { 
    var centerPoint = bar.getCenterPoint(); 
    ctx.fillText(dataset.data[index], centerPoint.x, centerPoint.y)); 
}),this) 

似乎“getCenterPoint”在版本2.1.3(您在示例中使用)中不可用。我试了它与2.5.0和它的工作