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.
8 * TextMeasure constructor.
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.
16 * @param {HTMLElement} element Element that has styles of measured text. The
17 * width of text is measures like as it is rendered in this element.
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 = [
34 for (var i = 0; i < stylesToBeCopied.length; i++) {
35 this.dummySpan_.style[stylesToBeCopied[i]] = styles[stylesToBeCopied[i]];
41 * Measures the width of text.
43 * @param {string} text Text that is measured the width.
44 * @return {number} Width of the specified text.
46 TextMeasure.prototype.getWidth = function(text) {
47 this.dummySpan_.innerText = text;
48 var rect = this.dummySpan_.getBoundingClientRect();
49 return rect ? rect.width : 0;