Created
March 13, 2019 14:12
-
-
Save felipebaltazar/e5797ae02c6a777b1cedbbfc4692dedf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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