Skip to content

Instantly share code, notes, and snippets.

@felipebaltazar
Created March 13, 2019 14:12
Show Gist options
  • Save felipebaltazar/e5797ae02c6a777b1cedbbfc4692dedf to your computer and use it in GitHub Desktop.
Save felipebaltazar/e5797ae02c6a777b1cedbbfc4692dedf to your computer and use it in GitHub Desktop.
function fitTextToview(view) {
const previousFontSize = view.style.fontSize;
const originalWidth = innerWidth(view);
const originalHeight = innerHeight(view);
var low = 5;
var high = originalHeight;
var mid = 0;
while (low <= high) {
mid = parseInt((low + high) / 2, 10);
view.style.fontSize = mid + 'px';
if (getTextNodeBounds(view).width <= originalWidth
&& getTextNodeBounds(view).height <= originalHeight ) {
low = mid + 1;
} else {
high = mid - 1;
}
}
view.style.fontSize = (mid - 1) + 'px';
const diff = fontSizeToPx(previousFontSize) -
fontSizeToPx(view.style.fontSize);
return diff > 1 || diff < -1;
}
function getTextNodeBounds(textNode) {
if (document.createRange) {
var range = document.createRange();
range.selectNodeContents(textNode);
if (range.getBoundingClientRect) {
return range.getBoundingClientRect();
}
}
return null;
}
function fontSizeToPx(fontSize) {
const pa = document.body;
const who = document.createElement('div');
who.style.cssText = 'display:inline-block; padding:0; line-height:1; position:absolute; visibility:hidden; font-size:'+ fontSize;
who.appendChild(document.createTextNode('W'));
pa.appendChild(who);
const fs = who.offsetHeight;
pa.removeChild(who);
return fs;
}
function innerHeight(el) {
const style = window.getComputedStyle(el, null);
return el.clientHeight -
parseInt(style.getPropertyValue('padding-top'), 10) -
parseInt(style.getPropertyValue('padding-bottom'), 10);
}
function innerWidth(el) {
const style = window.getComputedStyle(el, null);
return el.clientWidth -
parseInt(style.getPropertyValue('padding-left'), 10) -
parseInt(style.getPropertyValue('padding-right'), 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment