Chart.JS - 在点之上显示值

时间:2017-07-11 15:07:12

标签: javascript jquery canvas charts chart.js

晚上好,

我正在尝试构建代表API响应时间的折线图。问题是我在Chart.JS文档中找不到任何解决方案。有没有使用canvas api的本机解决方案或任何解决方案?

我希望图表看起来像这样: enter image description here

以下是我用来生成图表的代码

<script>
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: hoursArrFirst,

            datasets: [{
                label: 'First Brand API',
                data: timeArrProftit,
                borderWidth: 1,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.05)',
                    'rgba(255, 159, 64, 0.05)'
                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(255, 59, 64, 1)'
                ]
            },{
                label: 'Second Brand API',
                data: timeArrSecond,
                borderWidth: 1,
                backgroundColor: [
                    'rgba(132, 255, 99, 0.05)',
                    'rgba(64, 255, 159, 0.05)'
                ],
                borderColor: [
                    'rgba(32,155,99,1)',
                    'rgba(64,155, 59, 1)'
                ]
            },{
                label: 'Third Brand API' ,
                data: timeArrThird,
                borderWidth: 1,
                backgroundColor: [
                    'rgba(32, 99, 255, 0.05)',
                    'rgba(64, 59, 255, 0.05)'
                ],
                borderColor: [
                    'rgba(32, 99, 120, 1)',
                    'rgba(64, 59, 120, 1)'
                ]
            }]


        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });


</script>

1 个答案:

答案 0 :(得分:0)

在动画期间和之后调用一个函数

var options = {
    onAnimationProgress: function() { drawDatasetPointsLabels() },
    onAnimationComplete: function() { drawDatasetPointsLabels() }
}
function drawDatasetPointsLabels() {
        ctx.font = '.9rem sans-serif';
        ctx.fillStyle = '#AAA';
        ctx.textAlign="center";
        $(Trends.datasets).each(function(idx,dataset){
            $(dataset.points).each(function(pdx,pointinfo){
                // First dataset is shifted off the scale line. 
                // Don't write to the canvas for the null placeholder.
                if ( pointinfo.value !== null ) { 
                    ctx.fillText(pointinfo.value,pointinfo.x,pointinfo.y - 15);
                }
            });
        });         
     }