color.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { ChartInternal } from './core'
  2. import { notEmpty } from './util'
  3. ChartInternal.prototype.generateColor = function() {
  4. var $$ = this,
  5. config = $$.config,
  6. d3 = $$.d3,
  7. colors = config.data_colors,
  8. pattern = notEmpty(config.color_pattern)
  9. ? config.color_pattern
  10. : d3.schemeCategory10,
  11. callback = config.data_color,
  12. ids = []
  13. return function(d) {
  14. var id = d.id || (d.data && d.data.id) || d,
  15. color
  16. // if callback function is provided
  17. if (colors[id] instanceof Function) {
  18. color = colors[id](d)
  19. }
  20. // if specified, choose that color
  21. else if (colors[id]) {
  22. color = colors[id]
  23. }
  24. // if not specified, choose from pattern
  25. else {
  26. if (ids.indexOf(id) < 0) {
  27. ids.push(id)
  28. }
  29. color = pattern[ids.indexOf(id) % pattern.length]
  30. colors[id] = color
  31. }
  32. return callback instanceof Function ? callback(color, d) : color
  33. }
  34. }
  35. ChartInternal.prototype.generateLevelColor = function() {
  36. var $$ = this,
  37. config = $$.config,
  38. colors = config.color_pattern,
  39. threshold = config.color_threshold,
  40. asValue = threshold.unit === 'value',
  41. values =
  42. threshold.values && threshold.values.length ? threshold.values : [],
  43. max = threshold.max || 100
  44. return notEmpty(threshold) && notEmpty(colors)
  45. ? function(value) {
  46. var i,
  47. v,
  48. color = colors[colors.length - 1]
  49. for (i = 0; i < values.length; i++) {
  50. v = asValue ? value : (value * 100) / max
  51. if (v < values[i]) {
  52. color = colors[i]
  53. break
  54. }
  55. }
  56. return color
  57. }
  58. : null
  59. }