text.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.applyToText = exports.textOf = exports.getFont = exports.measureTextWidth = void 0;
  4. var util_1 = require("@antv/util");
  5. var ctx;
  6. /**
  7. * 计算文本在画布中的宽度
  8. */
  9. exports.measureTextWidth = (0, util_1.memoize)(function (text, font) {
  10. var content = (0, util_1.isString)(text) ? text : text.style.text.toString();
  11. var _a = font || (0, exports.getFont)(text), fontSize = _a.fontSize, fontFamily = _a.fontFamily, fontWeight = _a.fontWeight, fontStyle = _a.fontStyle, fontVariant = _a.fontVariant;
  12. if (!ctx) {
  13. ctx = document.createElement('canvas').getContext('2d');
  14. }
  15. ctx.font = [fontStyle, fontVariant, fontWeight, "".concat(fontSize, "px"), fontFamily].join(' ');
  16. return ctx.measureText(content).width;
  17. }, function (text, font) {
  18. return [(0, util_1.isString)(text) ? text : text.style.text.toString(), Object.values(font || (0, exports.getFont)(text)).join()].join('');
  19. });
  20. var getFont = function (textShape) {
  21. var fontFamily = textShape.style.fontFamily || 'sans-serif';
  22. var fontWeight = textShape.style.fontWeight || 'normal';
  23. var fontStyle = textShape.style.fontStyle || 'normal';
  24. var fontVariant = textShape.style.fontVariant;
  25. var fontSize = textShape.style.fontSize;
  26. fontSize = typeof fontSize === 'object' ? fontSize.value : fontSize;
  27. return { fontSize: fontSize, fontFamily: fontFamily, fontWeight: fontWeight, fontStyle: fontStyle, fontVariant: fontVariant };
  28. };
  29. exports.getFont = getFont;
  30. function textOf(node) {
  31. if (node.nodeName === 'text') {
  32. return node;
  33. }
  34. if (node.nodeName === 'g' && node.children.length === 1 && node.children[0].nodeName === 'text') {
  35. return node.children[0];
  36. }
  37. return null;
  38. }
  39. exports.textOf = textOf;
  40. function applyToText(node, style) {
  41. var text = textOf(node);
  42. if (text)
  43. text.attr(style);
  44. }
  45. exports.applyToText = applyToText;
  46. //# sourceMappingURL=text.js.map