|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +/** |
| 4 | + * A simple wrapper for system fonts to provide |
| 5 | + * @param {String} family Font Family (same as in CSS) |
| 6 | + * @param {Number} size Size in px |
| 7 | + * @constructor |
| 8 | + */ |
| 9 | +var FontMetrics = function(family, size) { |
| 10 | + this._family = family || (family = "Monaco, 'Courier New', Courier, monospace"); |
| 11 | + this._size = parseInt(size) || (size = 12); |
| 12 | + |
| 13 | + // Preparing container |
| 14 | + var line = document.createElement('div'), |
| 15 | + body = document.body; |
| 16 | + line.style.position = 'absolute'; |
| 17 | + line.style.whiteSpace = 'nowrap'; |
| 18 | + line.style.font = size + 'px ' + family; |
| 19 | + body.appendChild(line); |
| 20 | + |
| 21 | + // Now we can measure width and height of the letter |
| 22 | + line.innerHTML = 'm'; // It doesn't matter what text goes here |
| 23 | + this._width = line.offsetHeight; |
| 24 | + this._height = line.offsetHeight; |
| 25 | + |
| 26 | + // Now creating 1px sized item that will be aligned to baseline |
| 27 | + // to calculate baseline shift |
| 28 | + var span = document.createElement('span'); |
| 29 | + span.style.display = 'inline-block'; |
| 30 | + span.style.overflow = 'hidden'; |
| 31 | + span.style.width = '1px'; |
| 32 | + span.style.height = '1px'; |
| 33 | + line.appendChild(span); |
| 34 | + |
| 35 | + // Baseline is important for positioning text on canvas |
| 36 | + this._baseline = span.offsetTop + span.offsetHeight; |
| 37 | + |
| 38 | + document.body.removeChild(line); |
| 39 | +}; |
| 40 | + |
| 41 | +module.exports = FontMetrics; |
| 42 | + |
| 43 | +/** |
| 44 | + * Returns font family |
| 45 | + * @return {String} |
| 46 | + */ |
| 47 | +FontMetrics.prototype.getFamily = function() { |
| 48 | + return this._family; |
| 49 | +}; |
| 50 | + |
| 51 | +/** |
| 52 | + * Returns font family |
| 53 | + * @return {Number} |
| 54 | + */ |
| 55 | +FontMetrics.prototype.getSize = function() { |
| 56 | + return this._size; |
| 57 | +}; |
| 58 | + |
| 59 | +/** |
| 60 | + * Returns line height in px |
| 61 | + * @return {Number} |
| 62 | + */ |
| 63 | +FontMetrics.prototype.getHeight = function() { |
| 64 | + return this._height; |
| 65 | +}; |
| 66 | + |
| 67 | +/** |
| 68 | + * Returns line height in px |
| 69 | + * @return {Number} |
| 70 | + */ |
| 71 | +FontMetrics.prototype.getWidth = function() { |
| 72 | + return this._width; |
| 73 | +}; |
| 74 | + |
| 75 | +/** |
| 76 | + * Returns line height in px |
| 77 | + * @return {Number} |
| 78 | + */ |
| 79 | +FontMetrics.prototype.getBaseline = function() { |
| 80 | + return this._baseline; |
| 81 | +}; |
0 commit comments