Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add image to chart.js tooltip?

Tags:

chart.js

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 ?

like image 520
Shaniqwa Avatar asked Oct 20 '25 13:10

Shaniqwa


1 Answers

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/

like image 111
potatopeelings Avatar answered Oct 23 '25 08:10

potatopeelings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!