-
-
Save ayamflow/6955aab655d0cd63ffc3 to your computer and use it in GitHub Desktop.
Canvas fit letter height
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
'use strict'; | |
/* | |
This function will resize a letter until it fits the specified height | |
options: | |
- height: the height to fit | |
- precision: how much pixels +/- | |
- size: the start font size | |
- increment: the step of each iteration | |
*/ | |
module.exports = function fitLetterHeight(options) { | |
// height, precision, startSize, increment | |
var tester = document.createElement('div'); | |
tester.style.visibility = 'hidden'; | |
tester.style.position = 'absolute'; | |
tester.textContent = 'M'; // M is usually the biggest letter | |
document.body.appendChild(tester); | |
var fit = false; | |
var size = options.size - options.increment; | |
while (!fit) { | |
size += options.increment; | |
tester.style.fontSize = size + 'px'; | |
var h = tester.offsetHeight; | |
if (h >= options.height - options.precision) fit = true; | |
} | |
tester.parentNode.removeChild(tester); | |
return size; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment