Chart.js在工具提示和标签上添加图标 [英] Chartjs adding icon to tooltip and label

查看:88
本文介绍了Chart.js在工具提示和标签上添加图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在chartjs中的工具提示和y标签上添加前缀,但是问题是,当我放入< i class ='fa fa-sampleicon'>< / i> ,它以字符串形式返回,而不是您在图像上看到的html标记

I want to add a prefix to the tooltip and y-label in chartjs, but the problem is, when I put the <i class='fa fa-sampleicon'></i> it is returned as string not as an html tag as you can see on the image

这是我的代码:

<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>


推荐答案

我找到了答案,
基本上就像@jordanwillis所说的那样,它只是在画布上绘制的字符串,因此您不能添加html标签。

I've found an answer to this, So basically as @jordanwillis said, it's only string painted on canvas therefore you can't add html tags.

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

So the concept is to create a seperate div where you will put your custom tooltip(text / icons / image) onto, then positioning that div to where the default tooltip shows.

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

under my chart I added a new 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>

然后在我的脚本上:

I更改了我的默认工具提示配置以显示为false,因此不会妨碍我的新工具提示。

I changed my default tooltip configuration to show false so it wont get in the way of my new tooltip.

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

在lineOptions上,而不是调用回调

And at the lineOptions, instead of calling callbacks

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

我叫自定义,在这里您可以自由地操作自己的div和函数中的其他内容。

I've called custom, here you can freely manipulate your div and other things inside the function..

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");
                }
            }

        }

您想要获取的数据,您可以随时登录工具提示。它将为您提供数组对象的列表。

to get the data you wanted to get, you can always log the tooltip.. It'll give you the list of the array objects.

console.log(tooltip);

以下是我的自定义div的基本CSS:

Here is the basic css of my custom div:

#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);
 }

我从这些线程中收集了答案图表JS在工具提示中显示HTML 如何将图像添加到chart.js工具提示?

I've gathered my answer from these threads Chart JS Show HTML in Tooltip and How to add image to chart.js tooltip? and

这篇关于Chart.js在工具提示和标签上添加图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆