Chartjs 向工具提示和标签添加图标

Chr*_*her 3 html jquery chart.js

我想在chartjs中的工具提示和y标签中添加一个前缀,但问题是,当我把<i class='fa fa-sampleicon'></i>它作为字符串返回而不是作为你在图像上看到的html标签

标签和工具提示 chartjs

这是我的代码:

<script>

$(document).ready(function(){
    var lineLabel = <?php echo json_encode(array_reverse( $ch1_arrDate)); ?>;
    var dataVal1 = <?php echo json_encode(array_reverse( $ch1_arrRevenue_conf)); ?>;
    var dateFilter = <?php echo json_encode(array_reverse($ch1_arrDate2)); ?>;

    var lineData = {
        labels: lineLabel,
        datasets: [
            {
                label: 'Confirmed Revenue',
                backgroundColor: 'rgba(0,0,0,0.03)',
                data: dataVal1,
                borderColor: 'rgba(163,216,3,1)',
                borderWidth:1,
            },
        ]
    };


    var lineOptions = {
        responsive: true,
        maintainAspectRatio: true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    userCallback: function(value, index, values) {
                        return "<i class='fa fa-sampleicon'></i>"+addCommas(value);
                    }
                }
            }]
        },
        legend: {
            display: true,
            position: 'bottom'
        },
        tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              return "<i class='fa fa-sampleicon'></i>"+addCommas(tooltipItem.yLabel);
            }
          }
        }

    }


    var ctx = document.getElementById("chart1").getContext("2d");

    if($(window).width()>748){
        ctx.canvas.height = 160;
    }
    else{
        ctx.canvas.height = 300;
    }

    var chartDisplay = new Chart(ctx, {
        type: 'line',
        data: lineData,
        options: lineOptions
    });

    $("#chart1").click( 
       function(e){
            var activeLines= chartDisplay.getElementsAtEvent(e);
            var index = activeLines[0]["_index"];
            window.open(
            "dash_chartdeals.php?from=past&filter_date="+fixedEncodeURIComponent(dateFilter[index]),
            '_blank'
            )
    });


    $("#chart1").mouseenter(function(){
        $("#chart1").css("cursor", "pointer");
    });
});
function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

</script>
Run Code Online (Sandbox Code Playgroud)

Chr*_*her 6

我找到了一个答案,所以基本上正如@jordanwillis 所说,它只是画在画布上的字符串,因此你不能添加 html 标签。

因此,概念是创建一个单独的 div,您将在其中放置自定义工具提示(文本/图标/图像),然后将该 div 定位到默认工具提示显示的位置。

在我的图表下,我添加了一个新的 div chartjs-tooltip3

<div class="row">
    <div class="col-xs-12">
        <canvas id="chart3" width="500" height="300" style="border:1px solid #f1f1f1; padding:20px; padding-top:40px; box-shadow:2px 2px 2px rgba(0,0,0,0.2);"></canvas>
        <div id="chartjs-tooltip3"></div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

然后在我的脚本上:

我将我的默认工具提示配置更改为显示 false,这样它就不会妨碍我的新工具提示。

$(document).ready(function(){
    Chart.defaults.global.tooltips.enabled = false; //disable default tooltip
Run Code Online (Sandbox Code Playgroud)

而在 lineOptions,而不是调用回调

tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              return "<i class='fa fa-sampleicon'></i>"+addCommas(tooltipItem.yLabel);
            }
          }
        }
Run Code Online (Sandbox Code Playgroud)

我调用了custom,在这里你可以自由地操作你的div和函数内部的其他东西..

tooltips: {
            custom: function(tooltip) {
                var tooltipEl = $('#chartjs-tooltip3');

                if (!tooltip) {
                    tooltipEl.css({
                        opacity: 0
                    });
                    return;
                }

                if(tooltip.body){ // if the cursor hits the point

                    value = addCommas(tooltip.body["0"].lines["0"].substring(18)); //the data i need to add on my custom tooltip

                    tooltipEl.html(icon+" "+value); //icon is the html tag <i class="fa fa-sampleicon"></i>

                    //set the custom div to where the default tooltip is supposed to show.
                    tooltipEl.css({
                        opacity: 1,
                        left: tooltip.x + 'px',
                        top: tooltip.y + 'px',
                        fontFamily: this.fontFamily,
                        fontSize: this.fontSize,
                        fontStyle: this.fontStyle,
                    });
                    $("#chart3").css("cursor", "pointer");
                }
                else
                {
                    // if outside of the point, it'll hide the custom div
                    tooltipEl.css({
                        opacity: 0
                    });
                    //change my cursor to default
                    $("#chart3").css("cursor", "default");
                }
            }

        }
Run Code Online (Sandbox Code Playgroud)

要获取您想要的数据,您可以随时记录工具提示。它会给您数组对象的列表。

console.log(tooltip);
Run Code Online (Sandbox Code Playgroud)

这是我的自定义 div 的基本 css:

#chartjs-tooltip3{
     opacity: 0;
     position: absolute;
     background: rgba(0, 0, 0, .6);
     color: white;
     padding: 5px 12px 3px 12px;
     border-radius: 3px;
     -webkit-transition: all .1s ease;
     transition: all .2s ease;
     pointer-events: none;
     -webkit-transform: translate(-50%, 0);
     transform: translate(-50%, 0);
 }
Run Code Online (Sandbox Code Playgroud)

我从这些线程中收集了我的答案Chart JS Show HTML in TooltipHow to add image to chart.js tooltip?