text.js 1.7 KB

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