如何将图像添加到chart.js工具提示?
问题描述:
我正在使用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.
是吗可能吗?
答
您可以覆盖customTooltips函数。
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,
});
}
});
用图像URL替换pathTomyImage / myImage.png(您也可以使用部分内容从查找中选择[0]-这是x轴标签,或者更容易为图像命名,具体取决于轴标签。例如,January.png,February.png)
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)
确保还添加以下标记
<div id="chartjs-tooltip"></div>