答案 0 :(得分:3)
以下答案仅适用于Chart.js v2。
如果您需要v1解决方案,请查看pritishvaidya's。
您想使用图表选项的animation
属性:
options : {
animation: {
duration: 500,
onComplete: function () {
// The code here will be executed at the end of the animation
// (after 500ms here)
// You can get the canvas context using the following :
var ctx = this.chart.ctx;
// `this` being the chart instance
}
}
}
现在您要添加其上方点的值,这可以使用数据模型属性中的数据模型来完成:
onComplete: function() {
// You get the canvas context, to help you writing what you want
var ctx = this.chart.ctx;
// Here you set the context with what you need (font, size, color ...)
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.fillStyle = 'black';
// For every dataset ...
this.data.datasets.forEach(function(dataset) {
// For every data in the dataset ...
for (var i = 0; i < dataset.data.length; i++) {
// We get its model
var model = dataset._meta[0].data[i]._model;
// And write the data above it
ctx.fillText(dataset.data[i], model.x, model.y - 2);
// You can edit the last two arguments according to what you need
}
});
}
按照上面代码的结果,您可以找到on this jsFiddle:
答案 1 :(得分:1)
在图表js documentation上,您可以使用onAnimationComplete : function(){}
小提琴定义
<强> here 强>
您的 html 文件可能就像这样
<canvas id="my_chart"></canvas>
然后您的 js 文件可能如下所示
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data: [60, 80, 81, 56, 55, 40]
var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx).Line(chartData, {
showTooltips: false,
onAnimationComplete: function () {
//Your other ChartJs features defined here
var ctx = this.chart.ctx;
ctx.font = //your font
ctx.fillStyle = //your text color
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.points.forEach(function (points) {
ctx.fillText(points.value, points.x, points.y - 10);//You can change the x and y position of the text as per your requirement
});
})
}
});