Skip to content

Instantly share code, notes, and snippets.

@likr
Created August 31, 2020 19:51
Show Gist options
  • Save likr/8d03fb08ce2b7dfd36d29693e2f2e767 to your computer and use it in GitHub Desktop.
Save likr/8d03fb08ce2b7dfd36d29693e2f2e767 to your computer and use it in GitHub Desktop.
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