Skip to content

Instantly share code, notes, and snippets.

@ayamflow
Created January 23, 2016 20:27
Show Gist options
  • Save ayamflow/6955aab655d0cd63ffc3 to your computer and use it in GitHub Desktop.
Save ayamflow/6955aab655d0cd63ffc3 to your computer and use it in GitHub Desktop.
Canvas fit letter height
'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