auto-wrap.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { each } from '@antv/util';
  2. import { charAtLength, strLen } from '../../util/text';
  3. var WRAP_CODE = '\n';
  4. function wrapLabel(label, limitLength) {
  5. var text = label.attr('text');
  6. var labelLength = label.getBBox().width;
  7. var codeLength = strLen(text);
  8. var ellipsised = false;
  9. if (limitLength < labelLength) {
  10. var reseveLength = Math.floor((limitLength / labelLength) * codeLength);
  11. var newText = wrapText(text, reseveLength);
  12. label.attr('text', newText);
  13. ellipsised = true;
  14. }
  15. return ellipsised;
  16. }
  17. function wrapText(str, reseveLength) {
  18. var breakIndex = 0;
  19. var rst = '';
  20. for (var i = 0, index = 0; i < reseveLength;) {
  21. var charLength = charAtLength(str, index);
  22. if (i + charLength <= reseveLength) {
  23. rst += str[index];
  24. i += charAtLength(str, index);
  25. index++;
  26. breakIndex = index;
  27. }
  28. else {
  29. break;
  30. }
  31. }
  32. // 根据设计标准,文本折行不能超过两行
  33. var wrappedText = rst + WRAP_CODE + str.substring(breakIndex, str.length);
  34. return wrappedText;
  35. }
  36. export function wrapLabels(labelGroup, limitLength) {
  37. var children = labelGroup.getChildren();
  38. var wrapped = false;
  39. each(children, function (label) {
  40. var rst = wrapLabel(label, limitLength);
  41. wrapped = wrapped || rst;
  42. });
  43. return wrapped;
  44. }
  45. //# sourceMappingURL=auto-wrap.js.map