Highcharts确定文本是否在数据点之外

时间:2016-06-28 18:17:44

标签: javascript highcharts

我想知道是否有办法区分数据点在条形图内部或外部。

基本上,使用下面的图表

  • 我希望文本9178采用我生成的颜色(因为它位于条形图内)
  • 我希望其余的数字是黑色的(因为它们在酒吧之外)

我想知道API是否提供了一些我可以用编程方式来决定使用什么颜色的东西。 例如如果数据点有一个我可以调用的方法isOverflow(),那么如果它返回true,我可以将颜色设置为黑色。

enter image description here

在jsfiddle上创建:https://jsfiddle.net/Mingzilla/pjqhqn4u/6

var generateColor = function(item) {
  var lightColor = "#DADADA";
  var color = new Highcharts.Color(item.point.color).rgba;
  var isLightBg = color[0] + color[1] + color[2] > 384;
  return isLightBg ? '#000000' : lightColor;
};


$(function() {
  $('#container').highcharts({
    title: {
      text: 'I want data point inside a bar to be my colour, and outside to be black'
    },
    chart: {
      type: 'column'
    },
    xAxis: {
      categories: ['Car Insurance',
        'Life Insurance',
        'Pet Insurance'
      ]
    },
    plotOptions: {
      series: {
        dataLabels: {
          enabled: true,
          overflow: 'justify',
          style: {
            fontWeight: 'normal',
            textShadow: 'none'
          },
          formatter: function() {
            var item = this;
            return '<span style="fill:' +
              generateColor(item) + '">' +
              (item.point.formattedValue || item.point.y) +
              '</span>';
          }
        }
      }
    },

    series: [{
      "color": "#666699",
      "name": "North",
      "data": [{
        "color": "#666699",
        "name": "Car Insurance",
        "y": 9178
      }, {
        "color": "#666699",
        "name": "Life Insurance",
        "y": 4518
      }, {
        "color": "#666699",
        "name": "Pet Insurance",
        "y": 1450
      }]
    }, {
      "color": "#663366",
      "name": "South",
      "data": [{
        "color": "#663366",
        "name": "Car Insurance",
        "y": 2129
      }, {
        "color": "#663366",
        "name": "Life Insurance",
        "y": 1066
      }, {
        "color": "#663366",
        "name": "Pet Insurance",
        "y": 374
      }]
    }]

  });
});

1 个答案:

答案 0 :(得分:1)

默认颜色基于对比度或声明的单色。但是你可以为所有数据标签返回一种颜色(即黑色)。然后捕获图表对象中的加载/重绘事件以对所有dataLabel进行交互。在每个内部,都有关于位置和verticalAlign的信息,可用于检查标签的位置。如果这是顶部,请通过css()方法应用lightColor。

var lightColor = "#DADADA";

function datalabelColor() {
    var chart = this,
  series = chart.series,
  each = Highcharts.each,
  dL;

  each(series, function(serie, i) { 
    each(serie.data, function(p, j) {
      dL = p.dataLabel;

      if(dL.alignOptions.verticalAlign === 'top') {
        dL.css({
            color: lightColor
        });
      }
    });
  });
}

实施例: - https://jsfiddle.net/mys5k9ty/

如果您有任何其他问题,请与我们联系。

相关问题