font-metrics.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.FontMetrics = void 0;
  4. var util_1 = require("../core/util");
  5. var SAMPLE_TEXT = 'Hidden Text';
  6. var FontMetrics = /** @class */ (function () {
  7. function FontMetrics(document) {
  8. this._data = {};
  9. this._document = document;
  10. }
  11. FontMetrics.prototype.parseMetrics = function (fontFamily, fontSize) {
  12. var container = this._document.createElement('div');
  13. var img = this._document.createElement('img');
  14. var span = this._document.createElement('span');
  15. var body = this._document.body;
  16. container.style.visibility = 'hidden';
  17. container.style.fontFamily = fontFamily;
  18. container.style.fontSize = fontSize;
  19. container.style.margin = '0';
  20. container.style.padding = '0';
  21. container.style.whiteSpace = 'nowrap';
  22. body.appendChild(container);
  23. img.src = util_1.SMALL_IMAGE;
  24. img.width = 1;
  25. img.height = 1;
  26. img.style.margin = '0';
  27. img.style.padding = '0';
  28. img.style.verticalAlign = 'baseline';
  29. span.style.fontFamily = fontFamily;
  30. span.style.fontSize = fontSize;
  31. span.style.margin = '0';
  32. span.style.padding = '0';
  33. span.appendChild(this._document.createTextNode(SAMPLE_TEXT));
  34. container.appendChild(span);
  35. container.appendChild(img);
  36. var baseline = img.offsetTop - span.offsetTop + 2;
  37. container.removeChild(span);
  38. container.appendChild(this._document.createTextNode(SAMPLE_TEXT));
  39. container.style.lineHeight = 'normal';
  40. img.style.verticalAlign = 'super';
  41. var middle = img.offsetTop - container.offsetTop + 2;
  42. body.removeChild(container);
  43. return { baseline: baseline, middle: middle };
  44. };
  45. FontMetrics.prototype.getMetrics = function (fontFamily, fontSize) {
  46. var key = fontFamily + " " + fontSize;
  47. if (typeof this._data[key] === 'undefined') {
  48. this._data[key] = this.parseMetrics(fontFamily, fontSize);
  49. }
  50. return this._data[key];
  51. };
  52. return FontMetrics;
  53. }());
  54. exports.FontMetrics = FontMetrics;
  55. //# sourceMappingURL=font-metrics.js.map