I have an algorithm for reducing a font size in a given text box if the text is too big for the box (fit to box)
and it works just fine, but it's really inefficient as it's literally just reducing the font size by 1 till it fits.
Can anyone help me make it more efficient, such as binary chopping or something?
the code is:
function fitToBox(object, maxFontSize, minFontSize, maxHeight) {
var box = document.getElementById(object);
var currentHeight = box.offsetHeight;
var currentFontSize = maxFontSize;
do {
box.style.fontSize = currentFontSize+"pt";
currentFontSize = box.style.fontSize.replace("pt", "");
currentHeight = box.offsetHeight;
if(currentHeight >= maxHeight) {
currentFontSize -= 1;
}
} while (currentHeight > maxHeight && currentFontSize > minFontSize);
box.style.lineHeight = currentFontSize+"pt";
}
Complete example in HTML (just add more text to the div to see the fitting in progress)
<html>
<head>
<script type="text/javascript">
function fitToBox(object, maxFontSize, minFontSize, maxHeight) {
var box = document.getElementById(object);
var currentHeight = box.offsetHeight;
var currentFontSize = maxFontSize;
do {
box.style.fontSize = currentFontSize+"pt";
currentFontSize = box.style.fontSize.replace("pt", "");
currentHeight = box.offsetHeight;
if(currentHeight >= maxHeight) {
currentFontSize -= 1;
}
} while (currentHeight > maxHeight && currentFontSize > minFontSize);
box.style.lineHeight = currentFontSize+"pt";
}
</script>
</head>
<body>
<div id="fitme" style="background-color: yellow; font-size: 24pt; width: 400px;">
This is some text that is fit into the box This is some text that is fit into the box This is some text that is fit into the box
</div>
<script type="text/javascript">
fitToBox("fitme", 24, 4, 80);
</script>
</body>
</html>