nov*_*ato 2 javascript 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 %>"
});
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用...
我需要这样的东西:

var ctx = document.getElementById("myChart");你的代码中有定义吗?
更新
将此代码添加到您的选项对象:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/h4p8f5xL/
更新 2
用你想要的宽度和高度的容器包围你的画布
<div style="width: 100%; height: 500px">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)
并将以下内容添加到您的选项对象中
// 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,
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您想为每个元素呈现居中文本,有一种更简单的方法:
Chart.helpers.each(meta.data.forEach(function (bar, index) {
var centerPoint = bar.getCenterPoint();
ctx.fillText(dataset.data[index], centerPoint.x, centerPoint.y));
}),this)
Run Code Online (Sandbox Code Playgroud)
似乎“getCenterPoint”在版本 2.1.3 中不可用(您在示例中使用)。我用 2.5.0 尝试过,它可以工作
| 归档时间: |
|
| 查看次数: |
12615 次 |
| 最近记录: |