在Chart.js中更改工具提示颜色 [英] Changing tooltip color in Chart.js

查看:116
本文介绍了在Chart.js中更改工具提示颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试根据数据值自定义工具提示.在折线图的拐角处,折线图的拐角处也有这些小的圆形连接器或连接点,因此我也在尝试更改其颜色,对于那些我什至不知道从哪里开始的人.这是我正在使用的部分代码,试图通过Chart.js返回并更改工具提示颜色

trying to customized the tooltip based on the value of the data. Also there are these small circular connectors or joins on the corner of a line chart, when the line goes up or down, that I am also trying to change its color and for those I don't even know where to start. Here is a portion of the code I am using where I am trying to return and change the tooltip color using Chart.js

        tooltips: {
          mode: 'index',
          intersect: false,
          callbacks: {

            label: function(tooltipItem, data) {
              if (tooltipItem.yLabel === 1) {

    //return 'Normal';
            return { 'Normal',
             tooltipFillColor: 'rgb(255, 99, 132)', // red
        };

              } else if (tooltipItem.yLabel === 2) {

               // return 'Active';
        return { 'Acitve',
             tooltipFillColor: 'rgb(75, 192, 192)', // green
        };

              }
            }
          }
        },

感谢所有帮助!

推荐答案

您几乎想在除chart.js提供的配置选项之外自定义工具提示的外观时,都必须使用自定义工具提示.自定义工具提示的好处是它们基于html/css,因此您的样式选择无穷无尽.

Pretty much anytime you want to customize the look and feel of the tooltip beyond the configuration options provided by chart.js, you will have to use custom tooltips. The good thing about custom tooltips is that they are html/css based so your styling options are endless.

在这种情况下,由于您尝试根据数据值更改工具提示的背景颜色,因此您可以简单地定义一些css类来处理这两种样式选项,然后在自定义工具提示函数中实现逻辑以分配适当的基于值的css类.

In this case, since you are trying to change the tooltip background color based upon the value of your data, you can simply define some css classes to handle both styling options and then implement logic in your custom tooltip function to assign the appropriate css class based upon a value.

这里是一个例子.

custom: function(tooltip) {
  // get the tooltip element
  var tooltipEl = document.getElementById('chartjs-tooltip');

  // create one if it does not yet exist
  if (!tooltipEl) {
    tooltipEl = document.createElement('div');
    tooltipEl.id = 'chartjs-tooltip';
    tooltipEl.innerHTML = "<table></table>"
    document.body.appendChild(tooltipEl);
  }

  // hide the tooltip and restore the cursor
  // if there isn't one to display yet
  if (tooltip.opacity === 0) {
    tooltipEl.style.opacity = 0;
    $(this._chart.canvas).css("cursor", "default");
    return;
  } else {
    // otherwise change the cursor to pointer
    $(this._chart.canvas).css("cursor", "pointer");
  }

  // clear all classes and add the correct background color
  tooltipEl.classList.remove('active', 'normal');
  if (tooltip.dataPoints[0].yLabel === 2) {
    tooltipEl.classList.add('active');
  } else {
    tooltipEl.classList.add('normal');
  }

  function getBody(bodyItem) {
    return bodyItem.lines;
  }

  // set tooltip text
  if (tooltip.body) {
    var titleLines = tooltip.title || [];
    var bodyLines = tooltip.body.map(getBody);
    var innerHtml = '<thead>';

    titleLines.forEach(function(title) {
      innerHtml += '<tr><th>' + title + '</th></tr>';
    });
    innerHtml += '</thead><tbody>';

    bodyLines.forEach(function(body, i) {
      // map the number that is going to be displayed state value
      if (tooltip.dataPoints[0].yLabel === 2) {
        body = 'Active';
      } else {
        body = 'Normal';
      }

      var colors = tooltip.labelColors[i];
      var style = 'background:' + colors.backgroundColor;
      style += '; border-color:' + colors.borderColor;
      style += '; border-width: 2px'; 
      var span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
      innerHtml += '<tr><td>' + span + body + '</td></tr>';
    });
    innerHtml += '</tbody>';

    var tableRoot = tooltipEl.querySelector('table');
    tableRoot.innerHTML = innerHtml;
  }

  // get the position of tooltip
  var position = this._chart.canvas.getBoundingClientRect();

  // set display, position, and font styles
  tooltipEl.style.opacity = 1;
  tooltipEl.style.left = position.left + tooltip.caretX + 'px';
  tooltipEl.style.top = position.top + tooltip.caretY + 'px';
  tooltipEl.style.fontFamily = tooltip._fontFamily;
  tooltipEl.style.fontSize = tooltip.fontSize;
  tooltipEl.style.fontStyle = tooltip._fontStyle;
  tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
}

听起来您还想根据数据值自定义点颜色.这实际上很简单,不需要使用任何回调.您可以简单地将颜色数组传递给pointBackgroundColorpointBorderColor属性,其中颜色数组中的每个索引都映射到数据数组中的索引.

It also sounds like you want to customize the point color based upon the data value. This is actually quite simple to do and does not require using any sort of callback. You can simply pass an array of colors to the pointBackgroundColor and pointBorderColor properties where each index in the array maps to the index in your data array.

例如,如果您希望第一个点和第三个点具有不同的颜色,则您的数组可能看起来像这样[blue, red, blue, red].您可以在构建图表数据对象时构建颜色数组(例如,在prepareDataForChart()函数中.

For example, if you want the first and third points to be a different color then your array might look like this [blue, red, blue, red]. You can just build your color array while you are building your chart data object (e.g. in the prepareDataForChart() function.

这是一个例子.

// this function processess our raw data and converts
// it to a format that chart.js can understand
var prepareDataForChart = function(data) {
  var chartData = {
    data: [],
    pointColors: [],
  };

  data.forEach(function(d) {
    var yValue;
    var pointColor;

    // since we cannot use a category scale on the y-axis,
    // lets map the eventState to an arbitrary numerical value
    // and set the point color
    if (d.eventState === 'A') {
      yValue = 2;
      pointColor = chartColors.red;
    } else if (d.eventState === 'N') {
      yValue = 1;
      pointColor = chartColors.blue;
    }

    // we have to use the 'alternate' dataset format
    // in order to graph this correctly
    chartData.data.push({
      x: d.eventTime,
      y: yValue,
    });

    // add our point color to the colors array
    chartData.pointColors.push(pointColor);
  });

  return chartData;
};

然后,当您创建图表时,只需使用函数返回的pointColors数组即可.

Then when you create you chart just use the pointColors array that was returned by your function.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: "Object 1",
      fill: false,
      borderColor: chartColors.red,
      borderWidth: 2,
      backgroundColor: chartColors.white,
      pointBorderColor: chartData.pointColors,
      pointBackgroundColor: chartData.pointColors,
      pointBorderWidth: 1,
      pointHoverRadius: 5,
      pointHitRadius: 20,
      steppedLine: true,
      data: chartData.data,
    }]
  },
// ...rest of chart options...

下面是一个 codepen示例,该示例演示了所讨论的所有内容(彩色的工具提示和要点).

Here is a codepen example demonstrating everything that was discussed (colored tooltips and points).

这篇关于在Chart.js中更改工具提示颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆