How to add image to chart.js tooltip?

后端 未结 1 706
轮回少年
轮回少年 2021-01-06 14:50

i\'m using Chart.js to build a line graph by specific directions from a designer, and I want my tooltip to include a small icon.

is it possible ?

相关标签:
1条回答
  • 2021-01-06 15:30

    You can override the customTooltips function.

    var myLineChart = new Chart(ctx).Line(data, {
        customTooltips: function (tooltip) {
            var tooltipEl = $('#chartjs-tooltip');
    
            if (!tooltip) {
                tooltipEl.css({
                    opacity: 0
                });
                return;
            }
    
            tooltipEl.removeClass('above below');
            tooltipEl.addClass(tooltip.yAlign);
    
            // split out the label and value and make your own tooltip here
            var parts = tooltip.text.split(":");
            var innerHtml = '<img src="pathTomyImage/myImage.png"> <span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
            tooltipEl.html(innerHtml);
    
            tooltipEl.css({
                opacity: 1,
                left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
                top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
                fontFamily: tooltip.fontFamily,
                fontSize: tooltip.fontSize,
                fontStyle: tooltip.fontStyle,
            });
        }
    });
    

    Replace pathTomyImage/myImage.png with your image URL (you could also pick this from a lookup using parts[0] - which is the x axis label, or easier still give your images a name depending on the axis label. eg. January.png, February.png)

    Make sure you add the following markup as well

    <div id="chartjs-tooltip"></div>
    

    Fiddle - http://jsfiddle.net/02xrgy10/

    0 讨论(0)
提交回复
热议问题