Created
August 31, 2020 19:51
-
-
Save likr/8d03fb08ce2b7dfd36d29693e2f2e767 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
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