为工具提示方块设置自定义颜色 Chart.js

Set custom colours for tooltip squares Chart.js

使用 Chart.js 时,是否可以更改用于表示每个条形的工具提示中方块的颜色?

我注意到,当您更改 pointColor 值时,它会影响方块的颜色,但是您能否以某种方式使用不同于为 pointColor 设置的颜色的其他颜色,这样您就可以拥有每个方块设置为另一种颜色。

查看下面的 fiddle 示例,将鼠标悬停在其中一个条上,工具提示中的方块希望更改为纯红色和纯灰色,就像条的悬停状态一样。

JSFiddle:

https://jsfiddle.net/dyjr2812/

HTML:

<canvas id="bar" width="390" height="225"></canvas>

JavaScript:

//Bar chart with two bars
    var barData2 = {
        labels: ["John W", "Ben T", "Jenny H", "Samantha D", "Anothony P"],
        datasets: [
            {
                fillColor: "rgba(153, 153, 155, 0.4)",
                highlightFill: "#7C7C7C",
                strokeColor: "#7C7C7C",
                pointColor: "#7C7C7C",
                pointStrokeColor: "#7C7C7C",
                pointHighlightFill: "#fff",
                data: [25, 94, 68, 175, 66]
            },
            {
                fillColor: "rgba(236,166,166,0.4)",
                highlightFill: "#C3090A",
                strokeColor: "#f9090a",
                pointColor: "#fff",
                pointStrokeColor: "#C3090A",
                pointHighlightFill: "#f9090a",
                data: [134, 112, 92, 160, 52]
            }
        ]
    };
    options = {
        responsive: true,
        scaleFontSize: 11,
        bezierCurve: true
    };
    var ctx = $("#bar").get(0).getContext("2d");
    var myChart = new Chart(ctx).Bar(barData2, options);

您可以包裹 Chart.MultiTooltip 以放入您的颜色并调用实际的工具提示绘制。

var originalDraw = Chart.MultiTooltip.prototype.draw;
Chart.MultiTooltip.prototype.draw = function() {
    this.legendColors[0].fill = "green";
    this.legendColors[1].fill = "blue"
    originalDraw.call(this, arguments)
}

Fiddle - https://jsfiddle.net/fxts741r/