tooptip里怎么写两个格式化分别对应两个图
时间: 2023-08-03 17:03:43 浏览: 41
如果您要在一个 canvas 中绘制两个图表,并为它们分别定制 tooltip 的格式化,您可以使用 Chart.js 的回调函数来实现。以下是一个示例代码:
```javascript
options: {
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
if (tooltipItem.datasetIndex === 0) {
label += tooltipItem.yLabel.toFixed(2) + ' units';
} else {
label += '$' + tooltipItem.yLabel.toFixed(2);
}
return label;
}
}
}
},
data: {
datasets: [
{
label: 'Units Sold',
data: [10, 20, 30, 40, 50],
borderColor: 'red',
fill: false
}
]
},
data2: {
datasets: [
{
label: 'Total Revenue',
data: [50, 40, 30, 20, 10],
borderColor: 'blue',
fill: false
}
]
},
plugins: [{
afterInit: function(chart, options) {
chart.tooltip._model.bodyFontColor = ['red', 'blue'];
}
}]
```
在这个示例中,我们在 `data` 中定义了第一个数据集,用红色绘制了一个折线图。在 `data2` 中定义了第二个数据集,用蓝色绘制了另一个折线图。在 `options` 中,我们使用了 `callbacks` 选项来定义一个 `label` 回调函数。在这个函数中,我们通过 `tooltipItem.datasetIndex` 判断当前的 tooltip 属于哪个数据集,然后为其定制不同的格式。在这个示例中,我们将第一个数据集的 tooltip 内容设置为数据值加上字符串 'units',将第二个数据集的 tooltip 内容设置为数据值加上字符 '$'。在 `plugins` 中,我们使用 `afterInit` 钩子函数来修改 tooltip 的样式。具体来说,我们将 `chart.tooltip._model.bodyFontColor` 属性设为一个数组,其中的两个元素分别对应两个数据集的颜色。
这样,当您在图表上移动鼠标并触发 tooltip 时,您将看到每个数据集的 tooltip 都按照自己的格式进行显示,并且它们的颜色也分别对应各自的折线图。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)