使用chart js版本3,如何将自定义数据添加到外部工具提示中?

j0pj023g  于 2022-11-23  发布在  Chart.js
关注(0)|答案(2)|浏览(147)

使用Chart JS第3版。如何传入可供外部工具提示使用的自定义数据?
我想用HTML重新创建此工具提示。

我将按照本页上的“#外部(自定义)工具提示”示例进行操作:https://www.chartjs.org/docs/latest/configuration/tooltip.html但是我需要额外的数据来构建工具提示,比如图片url或产品ID?我该如何将其导入模型?

evrscar2

evrscar21#

您可以将任何自定义/高级数据放入数据集,例如(imgUrls、productIds、imgDataset):

var chartdata = {
            labels: ["Swimming", "Golf", "Soccer"],
    datasets: [{
        label: "Choices",
        data: [4, 10, 6],
        backgroundColor: ["#a19828", "#b15928", "#fb9a99"],
        imgDataUrls:['img1','img2','img3'],
        imgDataSet:'imgDataset',
        productIds:['id1','id2','id3'],
    }]
};

然后,您可以使用工具提示项上下文中的datasetIndex、dataIndex来获取自定义/高级数据。

// Index of the dataset the item comes from
datasetIndex: number,

    // Index of this data item in the dataset
dataIndex: number,

https://github.com/chartjs/Chart.js/blob/master/docs/samples/tooltip/html.md

vx6bjr1n

vx6bjr1n2#

我不知道你是如何得到数据的,所以我假设你是用某种方法把它和你的普通数据放在一起的。在这种情况下,你可以向数据集添加一个自定义属性,并把它传递给工具提示。然后,它将在以下命名空间中的外部处理程序的上下文中可用:context.tooltip.dataPoints[0].dataset[customPropertyName] .
然后,您可以创建一个图像元素并将其添加到头部:

titleLines.forEach(title => {
  const tr = document.createElement('tr');
  tr.style.borderWidth = 0;

  const th = document.createElement('th');
  th.style.borderWidth = 0;
  const text = document.createTextNode(title);
  th.appendChild(text);

  // THIS BLOCK ADDED
  const imageTh = document.createElement('th');
  th.style.borderWidth = 0;
  const image = document.createElement('img');
  image.style = 'width:20px'
  image.src = context.tooltip.dataPoints[0].dataset.url;
  imageTh.appendChild(image);

  tr.appendChild(th);
  tr.appendChild(imageTh);
  tableHead.appendChild(tr);
});

小提琴:https://jsfiddle.net/Leelenaleee/xhrs2wvc/17/
完整代码(因为堆栈片段似乎不喜欢创建元素):
第一次

相关问题