dodge.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const Adjust = require('./base');
  2. const each = require('@antv/util/lib/each');
  3. const MARGIN_RATIO = 1 / 2;
  4. const DODGE_RATIO = 1 / 2;
  5. class Dodge extends Adjust {
  6. _initDefaultCfg() {
  7. /**
  8. * 调整过程中,2个数据的间距
  9. * @type {Number}
  10. */
  11. this.marginRatio = MARGIN_RATIO;
  12. /**
  13. * 调整占单位宽度的比例,例如:占2个分类间距的 1/2
  14. * @type {Number}
  15. */
  16. this.dodgeRatio = DODGE_RATIO;
  17. this.adjustNames = [ 'x', 'y' ]; // 调整的维度,默认,x,y都做调整
  18. }
  19. getDodgeOffset(range, index, count) {
  20. const self = this;
  21. const pre = range.pre;
  22. const next = range.next;
  23. const tickLength = next - pre;
  24. const width = (tickLength * self.dodgeRatio) / count;
  25. const margin = self.marginRatio * width;
  26. const offset = 1 / 2 * (tickLength - (count) * width - (count - 1) * margin) +
  27. ((index + 1) * width + index * margin) -
  28. 1 / 2 * width - 1 / 2 * tickLength;
  29. return (pre + next) / 2 + offset;
  30. }
  31. processAdjust(dataArray) {
  32. const self = this;
  33. const count = dataArray.length;
  34. const xField = self.xField;
  35. each(dataArray, function(data, index) {
  36. for (let i = 0, len = data.length; i < len; i++) {
  37. const obj = data[i];
  38. const value = obj[xField];
  39. const range = {
  40. pre: len === 1 ? value - 1 : value - 0.5,
  41. next: len === 1 ? value + 1 : value + 0.5
  42. };
  43. const dodgeValue = self.getDodgeOffset(range, index, count);
  44. obj[xField] = dodgeValue;
  45. }
  46. });
  47. }
  48. }
  49. Adjust.Dodge = Dodge;
  50. module.exports = Dodge;