Chromium Code Reviews| 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 } | |
|
yoshiki
2013/08/30 10:41:40
Can you add 'Object.seal(this);'?
hirono
2013/08/30 11:46:02
Done.
| |
| 37 }; | |
| 38 | |
| 39 /** | |
| 40 * Measures the widht of text. | |
| 41 * | |
| 42 * @param {string} text Text that is measured the width. | |
| 43 * @return {number} Width of the specified text. | |
| 44 */ | |
| 45 TextMeasure.prototype.getWidth = function(text) { | |
| 46 this.dummySpan_.innerText = text; | |
| 47 var rect = this.dummySpan_.getBoundingClientRect(); | |
| 48 return rect ? rect.width : 0; | |
| 49 }; | |
| OLD | NEW |