图表JS传递点的自定义数据

时间:2017-04-03 12:45:47

标签: chart.js

我正在尝试创建一个折线图插件,它将在某些点下绘制参考字母。为此,该插件使用自定义 afterDatasetsDraw 函数来执行绘图。但是,我无法找到传递所需点的参考字母的方法。下面是我用红色圆圈字母试图实现的一个例子。

Chart with custom markers

有没有人知道如何传递相应点的引用字母?

感谢。

1 个答案:

答案 0 :(得分:1)

我只想为新插件定义一些配置属性,并使用其中一个属性来定义点引用的位置以及参考值应该是什么。

这是我的意思的一个例子。这将在图表的options属性中。

pointReferenceLetters: {
  display: true,
  fontColor: 'green',
  references: [
    {datasetIndex: 0, dataIndex: 1, reference: 'A'},
    {datasetIndex: 1, dataIndex: 2, reference: 'B'},
  ]
}

然后插件将使用此数据绘制点引用。这是一个示例,显示了插件如何使用此数据。注意,我只是做了一个快速实现来展示这个概念,这个插件不会像你那样绘制参考圈。

Chart.plugins.register({
  afterDraw: function(chartInstance) {
    if (chartInstance.config.options.pointReferenceLetters || chartInstance.config.options.pointReferenceLetters.display) {
      var references = chartInstance.config.options.pointReferenceLetters.references || [];
      var helpers = Chart.helpers;
      var ctx = chartInstance.chart.ctx;
      var fontColor = helpers.getValueOrDefault(chartInstance.config.options.pointReferenceLetters.fontColor, chartInstance.config.options.defaultFontColor);

      // render the value of the chart above the bar
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize + 5, 'normal', Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';
      ctx.fillStyle = fontColor;

      chartInstance.data.datasets.forEach(function (dataset, dsindex) {
        for (var i = 0; i < dataset.data.length; i++) {
          // note, many browsers don't support the array.find() function.
          // if you use this then be sure to provide a pollyfill
          var refPoint = references.find(function(e) {
            return e.datasetIndex == dsindex && e.dataIndex === i
          });

          if (refPoint) {         
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            ctx.fillText(refPoint.reference, model.x, model.y + 30);
          }
        }
      });
    }
  }
});

如您所见,插件使用pointReferenceLetters.references属性中提供的数据来确定何时应绘制点引用,然后使用提供的值作为参考文本。

这是展示所有这一切的codepen example