OLD | NEW |
(Empty) | |
| 1 // Copyright 2013 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 'use strict'; |
| 6 |
| 7 /** |
| 8 * TextMeasure constructor. |
| 9 * |
| 10 * TextMeasure is a measure for text that returns the width of text. This |
| 11 * class has a dummy span element. When measuring the width of text, it sets |
| 12 * the text to the element and obtains the element's size by |
| 13 * getBoundingClientRect. |
| 14 * |
| 15 * @constructor |
| 16 * @param {HTMLElement} element Element that has styles of measured text. The |
| 17 * width of text is mesures like as it is rendered in this element. |
| 18 */ |
| 19 var TextMeasure = function(element) { |
| 20 var doc = element.ownerDocument; |
| 21 this.dummySpan_ = doc.createElement('span'); |
| 22 this.dummySpan_ = doc.getElementsByTagName('body')[0]. |
| 23 appendChild(this.dummySpan_); |
| 24 this.dummySpan_.style.position = 'absolute'; |
| 25 this.dummySpan_.style.visibility = 'hidden'; |
| 26 var styles = window.getComputedStyle(element, ''); |
| 27 var stylesToBeCopied = [ |
| 28 'fontSize', |
| 29 'fontStyle', |
| 30 'fontWeight', |
| 31 'fontFamily', |
| 32 'letterSpacing' |
| 33 ]; |
| 34 for (var i = 0; i < stylesToBeCopied.length; i++) { |
| 35 this.dummySpan_.style[stylesToBeCopied[i]] = styles[stylesToBeCopied[i]]; |
| 36 } |
| 37 Object.seal(this); |
| 38 }; |
| 39 |
| 40 /** |
| 41 * Measures the widht of text. |
| 42 * |
| 43 * @param {string} text Text that is measured the width. |
| 44 * @return {number} Width of the specified text. |
| 45 */ |
| 46 TextMeasure.prototype.getWidth = function(text) { |
| 47 this.dummySpan_.innerText = text; |
| 48 var rect = this.dummySpan_.getBoundingClientRect(); |
| 49 return rect ? rect.width : 0; |
| 50 }; |
OLD | NEW |