在chart.js条形图上自定义工具提示

时间:2016-10-30 20:48:16

标签: javascript charts chart.js

我想在chart.js条形图上自定义工具提示。这是我的代码:

$(function () {
  var barData = no_houses_person

var barOptions = {
    scaleBeginAtZero: true,
    scaleShowGridLines: true,
    scaleGridLineColor: "rgba(0,0,0,.05)",
    legend: {
        display: true,
        position: 'top'
    },
    scaleGridLineWidth: 1,
    barShowStroke: true,
    barStrokeWidth: 1,
    barValueSpacing: 5,
    barDatasetSpacing: 1,
    responsive: true,
};
   var ctx = document.getElementById("barChart").getContext("2d");
   var myNewChart = new Chart(ctx, {
    type: 'bar',
    data: barData,
    options: barOptions
});
});

我尝试将tooltipTemplate: "<%if (label){%><%=label%> <%}%>(<%= value %> example)",添加到barOptions但它没有效果。

1 个答案:

答案 0 :(得分:8)

Chart.js在v2 +中从模板移动到Object interfaces,例如,如果您只想修改工具提示文本......

tooltips: {
    callbacks: {
        label: function(tooltipItem) {
            return "$" + Number(tooltipItem.yLabel) + " and so worth it !";
        }
    }
}

结果:

enter image description here

Codepen:Chart.js Custom Tooltip

对于更复杂的工具提示自定义,请在github上查看他们的示例:tooltips