chart.js - 使用图表颜色动态更改工具提示的背景颜色
解决方案
工作“动态”示例。
***请记住对与您的数据结构相关的数据的访问。
使用tooltip-model
https://www.chartjs.org/docs/2.7.3/configuration/tooltip.html#tooltip-model
“hello world”示例 - 将所有工具提示背景更改为red
:
tooltips: {
custom: function(tooltipModel) {
tooltipModel.backgroundColor = "red";
}
},
代码片段:
var data = {
labels: ["Africa", "Asia", "Europe", "America"],
datasets: [{
/* data */
label: "Population (millions)",
backgroundColor: ["red", "blue","green", 'purple'],
data: [1000,1500,2000, 2200]
}]
};
var options = {
title: {
text: 'Dynamically change tooltip background example',
display: true
},
tooltips: {
titleFontSize: 20,
borderWidth: 2,
borderColor: "white",
displayColors: false, /* if true, color boxes are shown in the tooltip */
/*########### Custom model ###########*/
custom: function(tooltipModel) {
/* if data & datasets not empty & tooltip available */
if (tooltipModel.opacity !== 0 && data.labels.length && data.datasets.length) {
/* get dataPoints index */
var index = tooltipModel.dataPoints[0].index;
/* get dataPoints datasetIndex */
var dataSetIndex = tooltipModel.dataPoints[0].datasetIndex;
/* get the current color on index and datasetIndex position */
var color = data.datasets[dataSetIndex].backgroundColor[index];
/* set backgroundColor */
tooltipModel.backgroundColor = color;
};
}
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
};
var myChart = new Chart(document.getElementById("chart"), {
type: 'bar',
data: data,
options: options
});
<canvas id="chart" width="800" height="450"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
代码概要
- “如果”(为了避免控制台错误):
/*########### Custom model ###########*/
custom: function(tooltipModel) {
/* if data & datasets not empty & tooltip available */
if (tooltipModel.opacity !== 0 && data.labels.length && data.datasets.length) {
/* do something */
console.log(tooltipModel.dataPoints[0]); /* return object */
console.log
返回对象:
Object {
datasetIndex: 0,
index: 1,
label: "Asia",
value: "1500",
x: 338.6845703125,
xLabel: "Asia",
y: 215.28,
yLabel: 1500
}
- 比我们
dot (.) notation
用来访问对象值的方式。
console.log(tooltipModel.dataPoints[0].index); /* return 1 */
- 我们使用这个索引“anchor”来获取
backgroundColor
数组的正确索引:
console.log(data.datasets[dataSetIndex].backgroundColor[index]); /* return "blue"
- 最后一步是使用这个颜色值:
/* set backgroundColor */
tooltipModel.backgroundColor = color;
用户界面
有用的隐藏 color boxes
:
displayColors: false, /* if true, color boxes are shown in the tooltip */
https://www.chartjs.org/docs/2.7.3/configuration/tooltip.html#tooltip-configuration
代码笔:
推荐阅读
- caching - 如何将清漆添加到拇指,s3 设置?
- wordpress - Wordpress 在主页上询问用户名和密码
- php - 页面总是重定向一次?
- swift - 'window' 不是 Swift iOS 开发中的标识符吗?
- typescript - 如何定义可以在所有类方法中使用的类变量
- python - 处理 requests.exceptions 的建议
- class - 类对象的实例如何用于构建应用程序?
- json - 如何将 JSON 记录插入 PowerApps 中的 Common Data Service 实体?
- javascript - html表单的Javascript验证不起作用
- reactjs - ReactJS RSS 提要到 Json 转换器