Entry
How do I get the rendered width/height of a string ?
How do I get the rendered with/height of the users default font size ?
How do I get the rendered with/height of a specific font family ?
Dec 14th, 2001 10:55
Scott Shattuck, Thor Larholm,
The only way to programmatically retrieve the rendered with or height
of some text is to output it into an empty element and retrieve the new
size of that element. An example for IE4+ and NS6+:
<div ID="PixelElement"
style="position:absolute;visibility:hidden;width:0px;height:0px"></div>
<script>
function getFontDimensions(sContent,sFont){
var D=document
var EL = D[D.getElementById?"getElementById":"all"]("PixelElement");
EL.style.font = sFont||"";
EL.innerHTML = sContent||"";
return {width:EL.offsetWidth,height:EL.offsetHeight};
}
var defaultSize = getFontDimensions("Some random string");
alert("width: " + defaultSize.width + "\neight: " + defaultSize.height);
var verdanaSize = getFontDimensions("X","Verdana");
alert("width: " + verdanaSize.width + "\neight: " + verdanaSize.height);
</script>
Note that writing to an empty layer in Nav4 will also allow you to
capture the font size as rendered. Using a CSS Style with the specific
font you'd like to test will provide data on fonts other than the user's
default font. This strategy can be used to dynamically compute the
necessary rows/cols data for textareas or the size value for text fields
to create text objects that fit pixel dimensions rather than character
sizes. (ss)