-
-
Save ver-1000000/dfefa92486d897c4deaaf3807fcfcef9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const optimalFontSize = (word, r, fontFamily, fontWeight) => { | |
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text') | |
text.textContent = word | |
text.setAttributeNS(null, 'font-family', fontFamily) | |
text.setAttributeNS(null, 'font-weight', fontWeight) | |
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg') | |
svg.appendChild(text) | |
document.body.appendChild(svg) | |
let ok = 0 | |
let ng = 100 | |
for (let iter = 0; iter < 10; ++iter) { | |
let m = (ok + ng) / 2 | |
text.setAttributeNS(null, 'font-size', m) | |
const { width, height } = text.getBBox() | |
const d = Math.sqrt(width ** 2 + height ** 2) / 2 | |
if (d <= r) { | |
ok = m | |
} else { | |
ng = m | |
} | |
} | |
document.body.removeChild(svg) | |
return ok | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment