UNPKG

html2canvas

Version:
90 lines (72 loc) 3 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.FontMetrics = void 0; var _Util = require("./Util"); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var SAMPLE_TEXT = 'Hidden Text'; var FontMetrics = /*#__PURE__*/ function () { function FontMetrics(document) { _classCallCheck(this, FontMetrics); this._data = {}; this._document = document; } _createClass(FontMetrics, [{ key: "_parseMetrics", value: function _parseMetrics(font) { var container = this._document.createElement('div'); var img = this._document.createElement('img'); var span = this._document.createElement('span'); var body = this._document.body; if (!body) { throw new Error(process.env.NODE_ENV !== "production" ? 'No document found for font metrics' : ''); } container.style.visibility = 'hidden'; container.style.fontFamily = font.fontFamily; container.style.fontSize = font.fontSize; container.style.margin = '0'; container.style.padding = '0'; body.appendChild(container); img.src = _Util.SMALL_IMAGE; img.width = 1; img.height = 1; img.style.margin = '0'; img.style.padding = '0'; img.style.verticalAlign = 'baseline'; span.style.fontFamily = font.fontFamily; span.style.fontSize = font.fontSize; span.style.margin = '0'; span.style.padding = '0'; span.appendChild(this._document.createTextNode(SAMPLE_TEXT)); container.appendChild(span); container.appendChild(img); var baseline = img.offsetTop - span.offsetTop + 2; container.removeChild(span); container.appendChild(this._document.createTextNode(SAMPLE_TEXT)); container.style.lineHeight = 'normal'; img.style.verticalAlign = 'super'; var middle = img.offsetTop - container.offsetTop + 2; body.removeChild(container); return { baseline: baseline, middle: middle }; } }, { key: "getMetrics", value: function getMetrics(font) { var key = "".concat(font.fontFamily, " ").concat(font.fontSize); if (this._data[key] === undefined) { this._data[key] = this._parseMetrics(font); } return this._data[key]; } }]); return FontMetrics; }(); exports.FontMetrics = FontMetrics;