auto-format.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { each } from '@antv/util';
  2. import { testLabel } from '../../util/label';
  3. import { strLen } from '../../util/text';
  4. function formatLabel(label, unit, suffix, precision) {
  5. var text = label.attr('text');
  6. // 轴的零值标签不参与格式化
  7. if (text === '0') {
  8. return text;
  9. }
  10. var value = parseFloat(text) / unit;
  11. var newText = formatText(value, precision);
  12. label.attr('text', "" + newText + suffix);
  13. }
  14. /** 根据显示空间获取数值format的精度 */
  15. function getPrecision(labels, unit, suffix, limitLength) {
  16. var values = [];
  17. var length = [];
  18. each(labels, function (label) {
  19. values.push(parseFloat(label.attr('text')) / unit);
  20. length.push(label.getBBox().width);
  21. });
  22. values.sort(function (a, b) {
  23. return b.toString().length - a.toString().length;
  24. });
  25. var maxLength = Math.max.apply(Math, length);
  26. var maxCodeLength = strLen(values[0].toString());
  27. var suffixLength = strLen(suffix);
  28. var reseveLength = Math.floor((limitLength / maxLength) * maxCodeLength) - suffixLength;
  29. // 先尝试保留小数点后两位
  30. var valueCodeLength = strLen(values[0].toFixed(2));
  31. if (valueCodeLength <= reseveLength) {
  32. return 2;
  33. }
  34. // 保留小数点后1位
  35. valueCodeLength = strLen(values[0].toFixed(1));
  36. if (valueCodeLength <= reseveLength) {
  37. return 1;
  38. }
  39. }
  40. function formatText(value, precision) {
  41. return value.toFixed(precision || 0);
  42. }
  43. export function formatLabels(labelGroup, limitLength, unit, suffix) {
  44. var children = labelGroup.getChildren();
  45. var needFormat = false;
  46. each(children, function (label) {
  47. var rst = testLabel(label, limitLength);
  48. if (rst === false) {
  49. needFormat = true;
  50. }
  51. });
  52. if (needFormat) {
  53. var precision_1 = getPrecision(children, unit, suffix, limitLength);
  54. each(children, function (label) {
  55. formatLabel(label, unit, suffix, precision_1);
  56. });
  57. return true;
  58. }
  59. return false;
  60. }
  61. //# sourceMappingURL=auto-format.js.map